Load div content from one page and show it to anot

2019-08-31 18:00发布

Couple of hours I am trying to load a div content from one page and show it to another. for example:

We have this wikipedia page. I want to get the content of the div with id="mw-content-text" and show it to my page that has element with id="result".

Is there a way to do it only with javascript/jquery?

标签: jquery load
5条回答
对你真心纯属浪费
2楼-- · 2019-08-31 18:16

dude, this may not possible according to the post

Origin is not allowed by Access-Control-Allow-Origin

查看更多
ら.Afraid
3楼-- · 2019-08-31 18:16

You can try iframe :

<iframe src="http://en.wikipedia.org/wiki/Robert_Bales" frameborder="0"></iframe>
查看更多
劳资没心,怎么记你
4楼-- · 2019-08-31 18:22

First download the JS file https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js and include the js file in your page. Below is the function that I used to load the external page.

   function test () {
     $.ajax({
       url: 'http://external_site.com',
       type: 'GET',
       success: function(res) {
         var content = $(res.responseText).text();
         alert(content);
       }
     });
   }

This worked for me getting content from external site.

Reference

查看更多
beautiful°
5楼-- · 2019-08-31 18:28

You can always use CURL in PHP, to grab content from other sites and then you can access the PHP and display it to the user on that page by using the load() JQuery function. Suppose this file is named: "gatherinfo.php" (JQuery can't gather information from remote sites since it's unsafe I believe (http://forum.jquery.com/topic/using-ajax-to-load-remote-url-not-working)) so one of the ways is to do it via PHP.

<?php
$myData = curl("http://en.wikipedia.org/wiki/Robert_Bales");
echo "$myData";

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
?>

However, make sure you always cite the sources when you gather information like that. Then by using JQuery you can call the file on your server and display it on the div you want by doing the following:

Javascript: (This will get initialized once the page is ready and has loaded)

$(document).ready(function(){
    $("#yourDIVID").load("gatherinfo.php");
});

HTML:

<html>
<head>
<script src="yourjqueryfile.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function(){
            $("#yourDIVID").load("gatherinfo.php");
        });
</script>
</head>
<body>
<div id="yourDIVID"> The content you're grabbing would load here </div>
</body>
</html>

That's how you would do it, if that's what you're planning to do.

查看更多
淡お忘
6楼-- · 2019-08-31 18:34

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');
查看更多
登录 后发表回答