How to get data with JavaScript from another server?

前端 未结 8 606
生来不讨喜
生来不讨喜 2020-12-02 17:23

How can I make requests to other server(s) (i.e. get a page from any desired server) with a JavaScript within the user\'s browser? There are limitations in place to prevent

相关标签:
8条回答
  • 2020-12-02 18:01

    update 2018:

    You can only access cross domain with the following 4 condition

    • in response header has Access-Control-Allow-Origin: *

    Demo

    $.ajax({
      url: 'https://api.myjson.com/bins/bq6eu',
      success: function(response){
        console.log(response.string);
      },
      error: function(response){
        console.log('server error');
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    • use server as bridge or proxy to the target

    Demo:

    $.ajax({
      url: 'https://cors-anywhere.herokuapp.com/http://whatismyip.akamai.com/',
      success: function(response){
        console.log('server IP: ' + response);
      },
      error: function(response){
        console.log('bridge server error');
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    • using browser addon to enable Allow-Control-Allow-Origin: *
    • disable browser web security

    Chrome

    chrome.exe --args --disable-web-security
    

    Firefox

    about:config -> security.fileuri.strict_origin_policy -> false
    

    end


    noob old answer 2011

    $.get(); can get data from jsbin.com but i don't know why it can't get data from another site like google.com

    $.get('http://jsbin.com/ufotu5', {},
      function(results){  alert(results); 
    });
    

    demo: http://jsfiddle.net/Xj234/ tested with firefox, chrome and safari.

    0 讨论(0)
  • 2020-12-02 18:04

    You will need to write a proxy on the server to do this. And all requests will be to your server and then your server will load html and send it back to client. And there are no good way to implement this via javascript only.
    jQuery contains functionality to load JSON data or external scripts using XmlHttpRequest but this functionality can not be used for html pages. Also you may check this thread of jQuery mailing list.

    0 讨论(0)
  • 2020-12-02 18:08

    You should check out jQuery. It has a rich base of AJAX functionality that can give you the power to do all of this. You can load in an external page, and parse it's HTML content with intuitive CSS-like selectors.

    An example using $.get();

    $.get("anotherPage.html", {}, function(results){
      alert(results); // will show the HTML from anotherPage.html
      alert($(results).find("div.scores").html()); // show "scores" div in results
    });
    

    For external domains I've had to author a local PHP script that will act as a middle-man. jQuery will call the local PHP script passing in another server's URL as an argument, the local PHP script will gather the data, and jQuery will read the data from the local PHP script.

    $.get("middleman.php", {"site":"http://www.google.com"}, function(results){
      alert(results); // middleman gives Google's HTML to jQuery
    });
    

    Giving middleman.php something along the lines of

    <?php
    
      // Do not use as-is, this is only an example.
      // $_GET["site"] set by jQuery as "http://www.google.com"
      print file_get_contents($_GET["site"]);
    
    ?>
    
    0 讨论(0)
  • 2020-12-02 18:08

    <script language="JavaScript" type="text/javascript" src="http://www.example.com/hello.js"></script>

    You add the data into hello.js in as an array, JSON or similar. Example: var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    Getting a JavaScript from another server doesn't much simpler.. :-)

    0 讨论(0)
  • 2020-12-02 18:19

    You can also use a iframe to emulate an ajax request. This saves you the mess of having to code a Backend solution for a Frontend problem. Here is an example:

    function setUploadEvent(typeComponet){
           var eventType = "";
           var iframe = document.getElementById("iframeId");
           try{
               /* for Mozilla / Opera9 */
               if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent)) {
                    eventType = "onload";
               }else{
               /* IE  */
                    eventType = "onreadystatechange";
               }
    
               iframe[eventType] = function(){
                    var doc = iframe.contentDocument || iframe.contentWindow.document;
                    var response = doc.body.innerHTML; /* or what ever content you are looking for */
                 }
               }
           catch(e){
               alert("Error loading content")}
           } 
    

    That should do the trick. Please note that the Browser detection line is not the cleanest, you should absolutely use the ones provided in all the most common JS frameworks (Prototype, JQuery, etc)

    0 讨论(0)
  • 2020-12-02 18:20

    Write a proxy script that forwards along the http request from your domain, this will bypass the XMLHttpRequest restrictions.

    If your using PHP, simply use cURL to request and read the page, then simply spit out the html as if it was from you domain.

    0 讨论(0)
提交回复
热议问题