使用JavaScript获取动态网页数据

时间:2015-05-19 04:52:43

标签: javascript

有人可以告诉我如何使用javascript获取动态网页数据或内容吗?

类似于php函数get_file_content() page_value = get_file_content(http://www.mywebsite.com/page.html);

但它是在javascript中。 有可能吗?

2 个答案:

答案 0 :(得分:0)

您必须使用Ajax

Javascript中的示例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","Your URL",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

您还可以查看Jquery Ajax Jquery Ajax Doc

Jquery Taken from Here

中的示例
$.ajax({
  url: 'getTwitterFollowers.php',
  type: 'GET',
  data: 'twitterUsername=jquery4u',
  success: function(data) {
    //called when successful
    $('#ajaxphp-results').html(data);
  },
  error: function(e) {
    //called when there is an error
    //console.log(e.message);
  }
});
-----------------------------------------------------
PHP - GET NUMBER FACEBOOK FANS & TWITTER FOLLOWERS
-----------------------------------------------------
< ?php
//get data passed to script
$username = htmlspecialchars(strip_tags($_GET["twitterUsername"]));

//get twitter followers
$api_page = 'http://twitter.com/users/show/' . $username;
$xml = file_get_contents ( $api_page );
$profile = new SimpleXMLElement ( $xml );
$count = $profile->followers_count;
$tfans = strval ( $count );

//get facebook likes
$fuser = json_decode(file_get_contents('http://graph.facebook.com/140918675956744/'));

//return result
echo "jQuery4u has " . $fuser->likes . " Facebook fans and " . $tfans . " Twitter followers.";
?>

对于跨域Ajax调用,您将需要JSONP 例 jsonp.php

<?php
    $callback ='mycallback';

    if(isset($_GET['mycallback']))
    {
        $callback = $_GET['mycallback'];
    }   
    $arr =array();
    $arr['name']="Ravishanker";
    $arr['age']=32; 
    $arr['location']="India";   

    echo $callback.'(' . json_encode($arr) . ')';

?>

JSONP的JQUery代码

$.ajax({
        url : "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
        dataType:"jsonp",
        jsonp:"mycallback",
        success:function(data)
        {
            alert("Name:"+data.name+"nage:"+data.age+"nlocation:"+data.location);
        }
    });

取自here

的示例

答案 1 :(得分:0)

我认为我有一个完美的解决方案。这可以通过YQL完成。这是代码。

<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  

  <script type="text/javascript">
    $(document).ready(function(){
      var container = $('#show');
      $('.ajaxtrigger').click(function(){

        doAjax($(this).attr('href'));
        return false;
      });
      function doAjax(url){
       alert(url);

var data = "http://ronwe.com/ronwe-marketing-suite/";
        if(url.match('^http')){
          $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                    "q=select%20*%20from%20html%20where%20url%3D%22"+
                    encodeURIComponent(data)+
                    "%22&format=xml'&callback=?",
            function(data){
              if(data.results[0]){
                var data = filterData(data.results[0]);
                container.html(data);

              } else {
                var errormsg = '<p>Error: could not load the page.</p>';
                container.html(errormsg);
              }
            }
          );
        } else {
          $('#target').load(url);
        }
      }
      function filterData(data){
        data = data.replace(/<?\/body[^>]*>/g,'');
        data = data.replace(/[\r|\n]+/g,'');
        data = data.replace(/<--[\S\s]*?-->/g,'');
        data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
        data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
        data = data.replace(/<script.*\/>/,'');
        return data;
      }
    });
  </script>

  </head>

  <body>
    <a href="http://ronwe.com/ronwe-marketing-suite/" class="ajaxtrigger loaded">Load Ajax Content<span> (ready.)</span></a>

    <div id="show">
    </div>
  </body>

</html>