How to make cross domain ajax call using jQuery JSONP

不羁的心 提交于 2019-12-07 02:59:26

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.

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"
});

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!