use jsonp to get xml cross domain

前端 未结 2 977
感动是毒
感动是毒 2020-12-11 03:19

I am trying to read xml into a webpage from another server, and I assume that my problem is Same-Origin Policy, and therefore a cross domain problem.

I have a bit of

相关标签:
2条回答
  • 2020-12-11 03:36

    If you have access to code generating the XML on the remote server, you can wrap the whole thing in jsonp.

    JSONP is a way of getting around the same-origin policy by obtaining data via using <script> tags rather than trying to remotely extract information.

    in your getconfiguation script, you would have something like

    callback("SERVER GENERATED XML/JSON DATA GOES HERE");
    

    where the callback is specified by the remote call

    For instance, if your remote script was php, you would make it look something like this:

    <?php
    // getconfiguration.php
    echo "$_GET['callback']($configuration_data);"
    ?>
    

    Then make run AJAX you provided in your question. What this actually does is dynamically insert a script tag into your page like this:

    <script src="http://192.168.0.106:8111/getconfiguation.php?callback=???"></script>
    

    jquery fills in the ??? for you with some unique wrapper it generated for your success callback

    0 讨论(0)
  • 2020-12-11 03:42

    If you don't have access to the server (if, for example, you're consuming an api) you can use YQL to convert your XML to jsonp and query the yahoo server from the browser using a custom custom YQL url (in which is embedded a SQL-like statement). Here's an example (for the zillow api):

    $('document').ready(function(){
      $.ajax({
        url: 'http://query.yahooapis.com/v1/public/yql?q=select * from zillow.search where address = "1835 73rd Ave NE" and citystatezip = "98039" and zwsid = "X1-ZWz1cse68iatcb_13bwv"&format=json&diagnostics=true&env=http://datatables.org/alltables.env&callback=mydata',
        jsonpCallback: "mydata",
        success: function(results) {
          console.log(results.query.results.searchresults.response.results.result.zpid);
        },
        dataType: 'jsonp'
      });
    });
    
    0 讨论(0)
提交回复
热议问题