JavaScript, JSONP and reading XML from cross-domai

2019-01-23 00:49发布

问题:

in my JS project I need to load data from cross-domain. (JavaScript sits on domain A, the data comes from domain B)

I have a solution that uses JSONP but I really need to load an XML instead (ordinary XML music playlist). The main goal is to be able to load and parse the XML data without the need to modify them first to some other format (like JSONP).

Is it completely impossible? Or are there any workarounds or hacks?

I am targeting mainly the latest browsers mainly on iOS.

Thanks!

PS: Could easyXDM be of any help? Or it's not relevant to XMLs?

UPDATE: unfortunately I can not use proxy, I am really asking about a direct solution.

回答1:

You can totally do this, just have your domain B return something like

func("<myxml></myxml>");

or

var someVar = "<myxml></myxml>";

The name JSONP doesn't really have anything to do with JSON specifically since its concept is all about executing JavaScript that has your data embedded in the code.

Once your domain B returns exactly one of those 2 forms above, domain A can simply use it either by doing:

<script>
function func(xmlString) {
    alert(xmlString); // you can parse the xmlString with 
                      // jQuery or something else
}
</script>

or if you use the second example:

<script>
alert(someVar);
</script>


回答2:

The usual solution is to have a "AJAX proxy" - a simple server-side script running on your domain, that fetches the data from the other domain and returns it unchanged.

The simplist is to give the script the URL you need the data from:

http://example.com/proxy.php?url=http%3A%2F%2Fexample.org%2Fajax%3Fid%3D123 gets the data from http://example.org/ajax?id=123

This can however be misused if you let any URL be fetched like that, so you should have your script, check that it actually only gets data from a specific URL.

In order to avoid having to parse the URL to check this, you could write a proxy specificly for your app, that only accesses the specific resource you need:

http://example.com/proxy.php?id=123 to access http://example.org/ajax?id=123.



回答3:

If you have a JSON-P solution in place, you can just pass the XML to the JSON-P callback as a string. You can then do XML parsing of a variable string in JavaScript



回答4:

The whole idea with JSONP is that the response must be executable as script. So sure, you can pass XML data back, as long as it's valid Javascript - for example, the server could wrap its response in a string:

myCallback('<xml><stuff/></xml>')

and you'd have to parse it with jQuery:

success: function(data) { 
    var xml = $(data); // now do stuff 
}

This assumes that you control the other server and/or someone who does is interested in formatting their data that way. Otherwise, you're out of luck, and need a proxy of some sort - you might be able to do this with YQL.