【发布时间】:2015-04-29 03:25:02
【问题描述】:
大家好,感谢您的宝贵时间。 这是我的javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
这是我的 .ashx 处理程序中的代码:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
当点击事件工作时,我的Ajaxrequest 似乎没有得到任何响应,因为成功时没有弹出警报。我已经使用浏览器的网络控制台进行了调试,它返回了预期的响应,但它似乎没有达到JavaScript 代码中的成功函数。欢迎任何见解或建议。谢谢。
【问题讨论】:
-
单个字符串不是有效的 json。添加错误处理程序会有所帮助。还要检查浏览器控制台的网络选项卡中的请求以获取线索
-
我已经编辑了我的帖子,但仍然无法弹出该警报。然而,这些帖子确实会发回 200 个响应状态。
-
更改 dataType: "text" 后让它工作
标签: javascript jquery asp.net ajax ashx