And*_*eas 9 jquery cross-domain jquery-post asp.net-web-api
我有一个奇怪的情况,我的jquery.post返回代码#200(OK),但错误处理程序被命中.
这是我的MVC WebAPI服务器端代码(它所做的只是返回代码#200 OK):
[HttpPost]
public HttpResponseMessage Post(T input)
{
//_handler.Create(input);
return Request.CreateResponse(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)
这是我的客户端脚本
ServerAccess.prototype.Save = function (m) {
$.post("http://localhost:55482/M/", m)
.success(
function (o) {
alert("success");
})
.error(
function (xhr, textStatus, errorThrown) {
if (typeof console == 'object' && typeof console.log == 'function') {
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
}
);
};
Run Code Online (Sandbox Code Playgroud)
Firebug中的控制台输出是:
POST
http://localhost:55482/M/200 OK 894ms头
响应标题
内容长度6
Content-Type application/json; 字符集= utf-8的
Date Sun,28 Oct 2012 18:55:17 GMT
服务器Microsoft-HTTPAPI/2.0
请求标题
接受 /
Accept-Encoding gzip,deflate
Accept-Language nb-no,nb; q = 0.9,no-no; q = 0.8,no; q = 0.6,nn-no; q = 0.5,nn; q = 0.4,en-us; q = 0.3,en ; q = 0.1
连接保持活着
内容长度21
Content-Type application/x-www-form-urlencoded; 字符集= UTF-8
主机localhost:55482
原点为null
User-Agent Mozilla/5.0(Windows NT 6.2; WOW64; rv:16.0)Gecko/20100101 Firefox/16.0
和
对象{readyState = 0,status = 0,statusText ="error"}
错误
(一个空字符串)
我浏览了周围,看到其他人有类似的问题,通常在响应中出现JSON格式错误.由于我只返回200 OK,没有内容,这似乎不适合我的情况.但是我确实试图像这样返回一个空对象
var o = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new T());
return Request.CreateResponse(HttpStatusCode.OK, o);
Run Code Online (Sandbox Code Playgroud)
服务器端从Visual Studio 2012运行,客户端只是一个带有一些.js文件的独立.html.另外,在VS中有一个断点我知道服务器收到了请求,而且Postman for Chrome的每个工作都很棒.
所以问题当然是:我在这里做错了什么?为什么错误处理程序命中?
谢谢!
试试这个:
ServerAccess.prototype.Save = function (m) {
$.ajax({
"type": "POST",
"url": "http://localhost:55482/M/",
"data": m,
"dataType": "json",
"success": function (data, textStatus, xhr) {
alert("success");
},
"error": function (xhr, textStatus, errorThrown) {
if (typeof console === 'object' && typeof console.log === 'function') {
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
}
});
};
Run Code Online (Sandbox Code Playgroud)
这允许您设置预期返回 MIME 类型application/json。
更新
如果您在 上运行独立的 HTML 页面http://localhost:55482,那么它不会是跨域的。如果您在其他地方或其他地方运行它file:///C:/Users/.../Desktop/test.htm,那么这将是跨域请求。http对比https:也有区别。
请求jsonp就是GET请求,不能是POST。这是因为jsonp请求是通过<script>向页面添加一个元素来实现的,其中源设置为您的 url,data并附加到查询字符串(加上时间戳参数)。任何POST期望jsonp返回的请求都应该自动转换为GET请求。
最后,由于您的例程需要返回数据,因此您需要返回一些实际数据,因为 jQuery 将尝试解析返回到对象中的 JSON(如果没有返回数据,则无法执行此操作),并且如果数据返回,则会抛出错误无法解析。
尝试将您的回复消息更改为:
String o = "success";
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
return Request.CreateResponse(HttpStatusCode.OK, ser.Serialize(o));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4309 次 |
| 最近记录: |