如何使用AJAX来加载新的页面到DIV如何使用、加载、页面、DIV

2023-09-10 18:08:17 作者:伊人ゞ

我的网站包含两个页面。我试图加载第2页为一个div一个页面上,然后的onclick显示2页。我尝试使用下面的code这是行不通的。我是个新手,所以我道歉,如果这仅仅是愚蠢的问题。

 <!DOCTYPE HTML>
< HTML>
< HEAD>
&所述;脚本的src =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js>
< / SCRIPT>
<脚本>
$(文件)。就绪(函数(){
  $(按钮)。点击(函数(){
    $阿贾克斯(网址:{url:myPage2.html,成功:函数(结果){
      $(#DIV1)HTML(结果);
    }});
  });
});
< / SCRIPT>
< /头>
<身体GT;

< D​​IV ID =div1的>< H2>让jQuery的AJAX更改此文字< / H>< / DIV>
<按钮>获取外部含量小于/按钮>

< /身体GT;
< / HTML>
 

解决方案

您的问题是不是你的code。正如你可以在这个Plnkr 的运行没有任何问题。

借助 .load() 功能可以简化您目前的code,但它不会解决你的实际问题,因为它只是语法糖。

由于某种原因,您的浏览器无法找到 myPage2.html ,因此无法正确显示。

请教一下,在jquery里能够先创建一个div,再在该div里使用load方法载入页面吗

My site consists of two pages. I'm trying to load Page 2 into a div on page one, then display page 2 onclick. I'm trying to use the following code which isn't working. I'm a newbie so my apologies if this is just dumb question.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url:"myPage2.html",success:function(result){
      $("#div1").html(result);
    }});
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>

</body>
</html>

解决方案

Your problem isn't your code. As you can see in this Plnkr it runs without any problems.

The .load() function can simplify your current code, but it won't solve your real problem, since it's just syntax sugar.

For some reason your browser fails to locate myPage2.html, and therefore can't display it correctly.

 
精彩推荐
图片推荐