我目前正在研究 ASP.NET WebApi 和 Angularjs
WebApi 有一个方法
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}
而且我必须从客户端调用这个方法。
当我使用 Ajax
调用此方法时,它不起作用,如果我使用 Ajax,方法参数 searchDetail
始终为 null。
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: "json",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
但是当我通过 HTTP
请求调用该方法时,它正在工作。
$http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Why? What is the difference between them? Why is Ajax not working and HTTP is?
最佳答案
jQuery 的 ajax()
发送内容类型为 x-www-form-urlencoded
的数据。
Angular 的 $http
发送 Content-type: application/json
您的服务器显然需要 JSON,但您为此设置了错误的 $.ajax()
调用。
根据 the docs :
方法
属性似乎不存在。type
属性应该确定请求的类型(例如“GET”、“POST”等)。- 为了将默认内容类型更改为
application/json
,您可以使用contentType
属性。
我自己还没有尝试过,但是像这样的东西应该可以工作:
$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});
关于javascript - HTTP请求和Ajax请求的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23579690/