简体   繁体   English

如何使用ajax将新页面加载到div中

[英]How to use ajax to load new page into div

My site consists of two pages. 我的网站由两页组成。 I'm trying to load Page 2 into a div on page one, then display page 2 onclick. 我正在尝试将第2页加载到第1页的div中,然后显示第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>

You have a # symbol in the load url. 您在加载网址中有一个#符号。

Also, why don't you use: 另外,你为什么不使用:

$("#div1").load("myPage2.html");

Your code should work once the # is removed from the URL. 从URL中删除#后,您的代码应该可以正常工作。 Here is a slightly more terse version: 这是一个稍微简洁的版本:

$("button").click(function(){
  $("#div1").load("myPage2.html");
});

see jQuery.load() jQuery.load()

Your problem isn't your code. 你的问题不是你的代码。 As you can see in this Plnkr it runs without any problems. 正如你在这个Plnkr中看到的,它运行没有任何问题。

The .load() function can simplify your current code, but it won't solve your real problem, since it's just syntax sugar. .load()函数可以简化您当前的代码,但它不能解决您的实际问题,因为它只是语法糖。

For some reason your browser fails to locate myPage2.html , and therefore can't display it correctly. 由于某种原因,您的浏览器无法找到myPage2.html ,因此无法正确显示它。

The # symbol in #myPage2.html is potentially the cause of your error. #myPage2.html中符号可能是导致错误的原因。

Aside from that, if you want, you could also do: 除此之外,如果你愿意,你也可以这样做:

$('button').click(function() {

    $('#div1').load('myPage2.html');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM