开发者

How to get HTML from external contents with Jquery?

I have successfully achieved the task of getting an internal webpage to show on my HTML, like I show bellow.

 <!doctype html>
 <html>
   <head>
  <script type="开发者_Python百科text/javascript" src="jquery-1.4.4.js"></script> 
   </head>
   <body> 
  <div id="target">
   click here to see teste1.html
  </div>
  <div id="result">

  </div>
  <script type="text/javascript">
   $('#target').click(function() {
    $.get('teste1.html', function(data) {
     $('#result').html(data);
     alert('Load was performed.');
    });
   });
  </script>
   </body>
 </html>

The main goal is to get an external webpage, but this is not working:

 $.get('http://www.google.com/index.html', function(data) {
  $('#result').html(data);
  alert('Load was performed.');
 });

I need to get the HTML from an external webpage to read the tags and then output to Json.

Some clues on how to achieve this(load external webpages with Jquery, or should I do it with PHP)?


This can't be done easily with Javascript due to the Same Origin Policy.

If it's just about displaying an external page, you could load it into an <iframe>.

Otherwise, if possible, use a server side language like PHP to act as a proxy. Fetch the data using Ajax from the proxy script. Take care to prevent misuse (like others misusing the script to make arbitrary requests).


Will you can't do it directly from JavaScript you will have to write a server-side script as a proxy, here is an example for you:

<?php
$url = urldecode($_GET['url']);
$handle = fopen(url,'r');
while (!feof($handle))
{
   $str = fgets($handle, 4096);
   echo $str;
}
fclose($handle);
?>

You can send AJAX request to the this script from JavaScript along with the URL of the site you want to get, remember to encode the URL before sending.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜