如何使用AJAX调用跨域的Web API? [英] how to call cross-domain web api using ajax?

查看:511
本文介绍了如何使用AJAX调用跨域的Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery.ajax({
           type: "GET",
           url: 'http://xxx.com/restaurant/VeryLogin(username,password)',
           dataType: "json",

           success: function (data) {
               alert(data);
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert("error");
           }
       });

我会提醒成功,但数据为空。该URL返回的XML数据,如果我们指定具体的数据类型,我们可以得到JSON数据,但在这里没有得到任何数据。

i alerts success,but data was null. The url returns xml data, if we specify the dataType we can get the json data,but here it was not getting any data.

任何帮助AP preciated。

Any help appreciated.

推荐答案

JavaScript是受到相同的域策略。这意味着安全JS脚本在客户端浏览器只能访问同一个域中,它是从哪里来的。

Javascript is subject to the same domain policy. This means for security a JS Script in a client browser can only access the same domain as it came from.

JSONP不受相同的限制。

JSONP is not subject to the same restrictions.

检查JSONP jQuery的文档在这里:

Check the jQuery docs on JSONP here:

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

下面是使用JSONP通过JQuery AJAX访问跨域服务的工作示例:

Here is a working example of using JSONP to access a cross-domain service via JQuery AJAX:

http://jsbin.com/idasay/4

和以防万一JSBIN删除该贴在未来的:

And just in case JSBIN deletes this paste in the future:

jQuery.ajax({
     type: "GET",
     url: 'http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo',
     dataType: "jsonp",
     cache: false,
     crossDomain: true,
     processData: true,


     success: function (data) {
         alert(JSON.stringify(data));
     },
     error: function (XMLHttpRequest, textStatus, errorThrown) {
         alert("error");
     }
 });

这篇关于如何使用AJAX调用跨域的Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆