JQuery AJAX方法在JSONP请求上调用“error”函数而不是“success”函数

时间:2015-06-25 04:46:56

标签: jquery asp.net .net asp.net-web-api cors

我无法从jQuery AJAX调用访问构建在.net framework 4.0上的asp.net web API。

WebAPI返回以下JSON结果

["Value1", "Value2"]

WebClient实现以下jQuery代码来访问WebAPI

$.ajax({
       type: 'GET',
       url: 'http://localhost:62915/api/values',
       contentType: 'application/json',
       dataType: "jsonp",
       success: function (data) {           
          alert('success');               
          console.log(data);
       },
       error: function (reason) {
           alert('fail');
           console.log(reason);
       }
});

我在chrome网络选项卡上没有收到任何错误消息,我可以看到预期的JSON结果。

但是,问题不是调用“成功”方法而是称之为“错误”方法。 我的jQuery代码有什么问题?

先谢谢。
--SJ

1 个答案:

答案 0 :(得分:3)

它可能是一个问题,你的API还不支持JSONP。你可以在一些步骤中使它工作。

  • 从nuget WebApiContrib.Formatting.Jsonp
  • 安装软件包
  • 在HttpConfiguration实例上调用扩展方法AddJsonpFormatter

它应该工作。

enter image description here

有关jsonp的更多详情:

https://en.wikipedia.org/wiki/JSONP

https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp