Ajax: Load content to a div from another div

时间:2015-11-12 11:36:02

标签: javascript jquery html ajax

I am trying to use ajax to change the content of a div (as html), when a link is clicked in that same div. I am not very skilled in ajax, so I am pretty sure that this is a noob question. I have tried searching the web for solutions, but I didn't manage to make anything work.

I have a div with the id "main" and inside it I am trying to make a link with the id "link01". When "link01" is clicked, I want "main" to load content from another div in another page ("txt2"-div in site2.html). But I can't get it to work.

Firstly, this is my index.html page:

<head>
    <title>site1</title>
    <meta charset="UTF-8">
</head>

<body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
            $('#link01').click(function() {
                $('#main').load('site2.html #txt2', function() {});
            });
        });
    </script>
    <div id="main">
        <a>
            <div id="link01">link</div>
        </a>
        Main div where the content will change</div>
    <br>
    <br>
</body>

</html>

And this is my site2.html page:

<!DOCTYPE html>
 <html>

<head>
    <title>Site2</title>
    <meta charset="UTF-8">

</head>

<body>

<div id="txt2">Text that will go into the main div at the index-page when link01 is clicked (contains links, images, etc)</div>

</body>

</html>

I have probably misunderstood something completeley.

1 个答案:

答案 0 :(得分:0)

There is a very bad practice way that may work... But you should really have a server side code that listens you your ajax call, and returns just the desired HTML fragment as a response. Having said that, try this, it MIGHT work (didn't check):

$(function() { 
  $('#link01').click(function(){
    $.ajax({
      url: 'site2.html',
      type: 'GET',
      success: function(data){
        data = $(data);
        var $div = $('#txt2', data);
        $('#main').html($div);
      }
    });   
  });
});