使用 Jquery 中的 Ajax() 函数将外部页面的 PART 加载到 div 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1628065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:53:03  来源:igfitidea点击:

Use Ajax() function in Jquery to load PART of an external page into div

jqueryloadexternalcallback

提问by user196986

I'm trying to load a DIV element from an external page into my current page using the Ajax/jQuery.ajax function. While I have successfully been able to load an entire external page, I can't seem to load justthe DIV element.

我正在尝试使用 Ajax/jQuery.ajax 函数将外部页面中的 DIV 元素加载到当前页面中。虽然我已经能够成功加载整个外部页面,但我似乎无法加载DIV 元素。

Here's my code:

这是我的代码:

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + "#external-div";
  $.ajax( {
  url: myUrl,
  success: function(html) {
    /* loads external content into current div element */
    $("#current-div").append(html);
    }
  });
  return false;
});

It grabs the HREF attribute without any trouble, but won't append "#external-div" to the URL. Any ideas?

它可以毫无困难地获取 HREF 属性,但不会将“#external-div”附加到 URL。有任何想法吗?

Thanks much!

非常感谢!

~Jared Crossley

~贾里德·克罗斯利

回答by Quintin Robinson

If you wanted to just return that div you could use the loadmethod of jQuery to simply load the content returned into your #current-divala

如果您只想返回该 div,您可以使用loadjQuery的方法简单地将返回的内容加载到您的#current-divala 中

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + " #external-div";
  $("#current-div").load(myUrl);
  return false;
});

Take a look at the jQuery Ajax/load documentation

查看jQuery Ajax/load 文档