Pan*_*hra 754 javascript asp.net ajax jquery json
我在我的网站上实现了一个Ajax请求,我从一个网页调用端点.它总是返回200 OK,但jQuery执行错误事件.我尝试了很多东西,但我无法弄清楚问题.我在下面添加我的代码:
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxSucceeded(result) {
    alert("hello");
    alert(result.d);
}
function AjaxFailed(result) {
    alert("hello1");
    alert(result.status + ' ' + result.statusText);
}
JqueryOpeartion.aspxprotected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
("Record deleted")成功删除后我需要字符串.我可以删除内容,但我没有收到此消息.这是正确的还是我做错了什么?解决这个问题的正确方法是什么?
Sal*_*n A 1068
jQuery.ajax尝试根据指定的dataType参数或Content-Type服务器发送的标头转换响应正文.如果转换失败(例如,如果JSON/XML无效),则会触发错误回调.
您的AJAX代码包含:
dataType: "json"
在这种情况下jQuery:
将响应评估为JSON并返回JavaScript对象.[...] JSON数据以严格的方式解析; 任何格式错误的JSON都会被拒绝,并抛出一个解析错误.[...]空的回应也被拒绝; 服务器应该返回null或{}的响应.
您的服务器端代码返回带有200 OK状态的HTML代码段.jQuery期待有效的JSON,因此会触发错误回调抱怨parseerror.
解决方案是dataType从jQuery代码中删除参数并使服务器端代码返回:
Content-Type: application/javascript
alert("Record Deleted");
但我宁愿建议返回JSON响应并在成功回调中显示消息:
Content-Type: application/json
{"message": "Record deleted"}
jak*_*ent 31
我使用多个空格分隔的dataTypes(jQuery 1.5+)有好运.如:
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
小智 29
您只需在AJAX调用中删除dataType:"json"即可
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json', //**** REMOVE THIS LINE ****//
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
Cor*_*vin 21
这只是为了记录,因为我在寻找解决我的问题的解决方案时碰到了这个帖子,类似于OP.
在我的情况下,由于Chrome中的同源策略,我的jQuery Ajax请求无法成功.当我修改我的服务器(Node.js)时,所有问题都解决了:
response.writeHead(200,
          {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "http://localhost:8080"
        });
它花了我一个小时的时间撞到了墙上.我感觉很蠢......
Lef*_*tyX 15
我估计你的aspx页面不会返回JSON对象.你的页面应该做这样的事情(page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
另外,尝试更改AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus 应该给你带来的错误类型.
使用以下代码确保响应为 JSON 格式(PHP 版本)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
| 归档时间: | 
 | 
| 查看次数: | 343402 次 | 
| 最近记录: |