Search code examples
jqueryajaxxmljsonp

Cross Domain JSONP XML Response


I am making a api cross domain request using JSONP and the external server returns me result in XML, below is my code:

$.ajax({
    type: "Get",
    url: "http://domain.com/function?Data=1234567890",
    xhrFields: {withCredentials: true},
    dataType: "JSONP text xml",
    contentType: "application/xml",
    cache: false,
    success: function(xml)
    {
    alert($(this).find('ResponseStatus').text());
    }
});

it returns me a xml but along with that it generates an error saying "Unexpected token <" which unfortunately stops my processing and i dont get an alert message. Any idea?

Best


Solution

  • As mentioned in the comments above, cross domain xml from javascript is a no-no unless you have control over the application that is spitting out the XML and can use a formatting trick to 'fool' the script into parsing it as JSON. If you can do that though, the question would have to be why not just format as JSON in the first place? So... Options

    1. Format the output from the application for handling with JSONP. Assuming that you can't do that in your case then...
    2. Use a local proxy on your webserver. There are plenty of simple proxy examples out there in PHP, python or any other language that doesn't have cross-domain restrictions. As far as your script on the page is then concerned it's a local AJAX request. If you can't do that then...
    3. One possibility would be to use an intermediary like yql. yql and jquery can make a lot of these xml problems go away. Downside of course is that you are sending things through a third party that you have no control over.

    Something like this:

    // find some demo xml - DuckDuckGo is great for this
        var xmlSource = "http://api.duckduckgo.com/?q=StackOverflow&format=xml"
    
    // build the yql query. Could be just a string - I think join makes easier reading
        var yqlURL = [
            "http://query.yahooapis.com/v1/public/yql",
            "?q=" + encodeURIComponent("select * from xml where url='" + xmlSource + "'"),
            "&format=xml&callback=?"
        ].join("");
    
    // Now do the AJAX heavy lifting        
        $.getJSON(yqlURL, function(data){
            xmlContent = $(data.results[0]);
            var Abstract = $(xmlContent).find("Abstract").text();
            console.log(Abstract);
        });
    

    Of course, in that example you are bringing back all the xml data and searching it locally - the option is there to tune the select statement to bring back just what you want.

    Hope that helps