开发者

use jsonp to get xml cross domain

I am trying to r开发者_运维问答ead 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 googling and it seems that jsonp is the way forward. Based on some examples I found here on stackoverflow and another sites, this is what I have, and it does not "hit" the server with the xml. I can view the xml in a browser.

$(document).ready(function(){    
   $.ajax({
        type: 'GET',
        dataType: 'jsonp',                
        url: 'http://192.168.0.106:8111/getconfiguration?',
        success: function (xml) 
        { //do stuff with received xml 
        }});    

Any suggestions? please keep in mind that I am a newbie with regards to JS / JQuery ;o)


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'
  });
});


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜