Jquery Ajax 调用 WEB API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19724857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Ajax Call to WEB API
提问by chamara
I'm trying to make a simple jquery ajax call to a WEB API method.
我正在尝试对 WEB API 方法进行简单的 jquery ajax 调用。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API action:
WEB API 操作:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
ajax call does not hitting the WEB API. I get the below error in browser console.
ajax 调用不会访问 WEB API。我在浏览器控制台中收到以下错误。
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850400 (Bad Request)
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850400(错误请求)
回答by elolos
You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
您尚未包含路由设置的代码,但假设它是正确的,则问题可能是由于您在尝试使用 POST 请求命中 WebApi 方法时将其命名为“Get”。发生这种情况是因为 WebApi 试图从操作名称中找出 HTTP 动词。
I would suggest either renaming the action or adding the [HttpPost]
attribute to your action method. You may also try the WebApiRouteDebuggerpackage.
我建议重命名操作或将[HttpPost]
属性添加到您的操作方法中。您也可以尝试WebApiRouteDebugger包。
回答by Francis
Unless you are doing a cross domain call, there is no need to use jsonp (jsonp also requires a custom formatter in Web API).
除非你是做跨域调用,否则没有必要使用jsonp(jsonp还需要Web API中的自定义格式化程序)。
$.getJSON('http://redrock.com:6606/api/values', function(data){
console.log(data);
});
EDIT:
编辑:
To install a jsonp media type formatter, have a look at this project: https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
要安装 jsonp 媒体类型格式化程序,请查看此项目:https: //github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
- Download the formatter using nuget
- Register the formatter
- Update your routeconfig
- 使用 nuget 下载格式化程序
- 注册格式化程序
- 更新您的路由配置