简体   繁体   English

Ajax:将内容从另一个div加载到div

[英]Ajax: Load content to a div from another div

I am trying to use ajax to change the content of a div (as html), when a link is clicked in that same div. 当在同一div中单击链接时,我尝试使用ajax更改div(如html)的内容。 I am not very skilled in ajax, so I am pretty sure that this is a noob question. 我对ajax不太熟练,所以我很确定这是一个菜鸟问题。 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". 我有一个ID为“ main”的div,并且在其中试图建立一个ID为“ link01”的链接。 When "link01" is clicked, I want "main" to load content from another div in another page ("txt2"-div in site2.html). 单击“ link01”时,我希望“ main”从另一个页面(site2.html中的“ txt2” -div)的另一个div加载内容。 But I can't get it to work. 但是我无法正常工作。

Firstly, this is my index.html page: 首先,这是我的index.html页面:

<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: 这是我的site2.html页面:

<!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. 我可能误会了completeley。

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. 可能有一种非常糟糕的练习方式……但是,您实际上应该有一个服务器端代码,可以监听您的ajax调用,并仅返回所需的HTML片段作为响应。 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);
      }
    });   
  });
}); 

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

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