简体   繁体   中英

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. 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. Here is a slightly more terse version:

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

see jQuery.load()

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.

The # symbol in #myPage2.html is potentially the cause of your error.

Aside from that, if you want, you could also do:

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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