如何使用ajax调用跨域web api?

tir*_*iru 6 asp.net ajax wcf-web-api

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

           success: function (data) {
               alert(data);
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert("error");
           }
       });
Run Code Online (Sandbox Code Playgroud)

它提醒成功,但数据为空.url返回xml数据,如果我们指定dataType,我们可以获取json数据,但是这里没有获取任何数据.

任何帮助赞赏.

pmc*_*own 9

Javascript受相同域策略的约束.这意味着为了安全起见,客户端浏览器中的JS脚本只能访问它来自的相同域.

JSONP不受相同的限制.

在这里查看JSONP上的jQuery文档:

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

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

http://jsbin.com/idasay/4

以防JSBIN将来删除此粘贴:

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");
     }
 });
Run Code Online (Sandbox Code Playgroud)