asp.net - 如何使用ajax调用跨域Web API?

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

它会警告成功,但数据为空。 url返回xml数据,如果指定dataType,则可以获取json数据,但此处未获取任何数据。

任何帮助表示赞赏。

最佳答案

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

关于asp.net - 如何使用ajax调用跨域Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9890034/

相关文章:

c# - 与错误代码 : 10413 集成的购物车运费

jquery - googlebot 是否会抓取 jQuery $.get() 调用中的网址并且可以阻止吗?

c# - Web API OData V4 开放类型 - 如何配置 Controller 和数据上下文

asp.net - WebForms 查看引擎文档?

asp.net - 有谁知道在 asp.net ListView 中隐藏列的方法?

php - 简单的 AJAX 文件上传表单不起作用

javascript - 如何拦截包括表单提交在内的所有http请求

json - 如何在字符串中传递 Json 数组 - asp 中的 webapi

C# WCF Web Api 4 MaxReceivedMessageSize

c# - 使用 CaSTLe Windsor 在 WebAPI 中进行依赖注入(inject)