Gentenator
Gentenator

Reputation: 207

Javascript Cross Domain Web Service Call

I'm trying to call a .NET web service, from javascript, that returns an XML document. The web service is located on a different web server than my app. I do not have control over the web service. I have successfully called the service using jQuery setting the dataType to jsonp and I can see that the XML document is returned in Firebug. However, I get an error in the Firebug console "missing ; before statement" where it looks like it's trying to parse the returned xml (to json maybe??). Any ideas or what's the best way to call a cross domain web service that returns xml? Many Thanks!

Upvotes: 0

Views: 1274

Answers (4)

Aaron
Aaron

Reputation: 5227

One possibility is to avoid using JSON altogether and use cURL and a PHP proxy instead. Send the data to a PHP script on your server, which then forms a cURL session with the script on the other domain and returns to result to the original AJAX caller.

Upvotes: 0

Zefiryn
Zefiryn

Reputation: 2265

If you set dataType to jsonp you should get response wrapped in the function call. For example if you expect to get

object {"key": "value"} 

the response for jsonp should be

parseRespone({"key":"value"});

The reason for this is that jsonp adds <script> tag to your page header so it should append valid javascript code there.

If you have no possibility to contact with the developers of the server I would suggest to make ajax call to your page where the page would make curl connection to the .NET server and retrives the response in pure json.

Upvotes: 0

Quentin
Quentin

Reputation: 943556

The JSON-P data format is a JavaScript program. If you use JSON-P then the data you get back must be JavaScript.

JSON-P works by loading the document using a <script> element (and that is never going to work for arbitrary XML data)

Your options are:

  1. Persuade whomever does control the web service to give you a JSON-P interface
  2. Persuade whomever does control the web service to grant your site permission to access it via CORS (Note limited browser support)
  3. Proxy the web service through your own server so your JS is operating on the same origin

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Someting like this:

$.getJSON("http://yoursite.com/xml2json.php?callback=?",
  {feed:"http://agency.nd.edu/agencynd-team.xml"},
    function(data) {
      // process data here
    }
});

<?php
header('content-type: application/json; charset=utf-8');

if( strlen($_GET["feed"]) > 13 ) {
  $xml = file_get_contents(urldecode($_GET["feed"]));
  if($xml) {
    $data = @simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($data);

    echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
  }
}
?>

Upvotes: 0

Related Questions