user817507
user817507

Reputation:

How to make cross domain ajax call using jQuery JSONP

What should I Change the below code to load XML cross domain using jsonp..

$.ajax({
    type: "GET",
    url: "http://www.w3schools.com/xml/note.xml",
    dataType: "xml",
    success: function(xml) {
        alert('Hi');
    }
});

Hope my problem is resolved.

Upvotes: 1

Views: 4302

Answers (4)

Rajendra
Rajendra

Reputation: 11

Cross Domain using JSONP is not possible in some scenarios. Please find the below URL for Cross Domain AJAX Request using Jquery directly or using XDomainRequest object http://rajendrapathi.webs.com/apps/forums/show/14007722-jquery-and-javascript

Upvotes: 1

ghusse
ghusse

Reputation: 3210

You cannot load XML with jsonp, because data have to be written in json in a certain way.

Let's assume that your current data is something like that:

<address>
  <fullname>John Doe</fullname>
  <street>1st street</street>
  <number>345</number>
  <zip>12345</zip>
  <city>Nowhere</city>
</address>

You'll have to send it in JSON, something like that:

{
  fullname: "John Doe",
  street: "1st street",
  number: 345,
  zip: "12345",
  city: "Nowhere"
}

Moreover, if you need to receive it through JSONP, you'll need to make another modification. Let's say that you're sending your request like that:

$.ajax({
  type: "GET",
  url: "http://www.w3schools.com/json/note.js",
  dataType: "jsonp",
  success: function(data) {
    alert('Hi');
  }
});

When calling the web service, jQuery will add a parameter named callback in the request URL.

Let's say the generated URL is: http://www.w3schools.com/json/note.js?callback=callback1234

Then, your json output will need to look like this:

callback1234({
  fullname: "John Doe",
  street: "1st street",
  number: 345,
  zip: "12345",
  city: "Nowhere"
});

Upvotes: 3

Alnitak
Alnitak

Reputation: 340055

As far as I know you can't (directly) load XML data using JSONP.

Cross-site AJAX with JSONP relies on wrapping the required object inside a Javascript function call that's executed inside a dynamically created <script> tag, and there's no mechanism for doing that with XML.

Even JSONP requires that the remote server perform the JSON wrapping - a CGI script outputing JSON data doesn't automatically support JSONP out of the box.

That's clearly going to be impossible if your data is actually plain XML files sat on an standard FTP server.

Upvotes: 1

Filip
Filip

Reputation: 2522

I think dataType should be JSONP if you want to receive JSONP.

http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Related Questions