JavaScript, JSONP and reading XML from cross-domain

前端 未结 4 1504
离开以前
离开以前 2020-12-15 01:58

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 ne

相关标签:
4条回答
  • 2020-12-15 02:43

    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.

    0 讨论(0)
  • 2020-12-15 02:49

    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>
    
    0 讨论(0)
  • 2020-12-15 02:52

    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.

    0 讨论(0)
  • 2020-12-15 02:53

    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

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