首页 文章

Ajax请求返回200 OK,但是触发了错误事件而不是成功

提问于
浏览
667

我在我的网站上实现了一个Ajax请求,我从一个网页调用 endpoints . 它总是返回 200 OK ,但jQuery执行错误事件 . 我尝试了很多东西,但我无法弄清楚问题 . 我在下面添加我的代码:

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);
}

C#代码为JqueryOpeartion.aspx

protected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}

删除成功后我需要 ("Record deleted") 字符串 . 我可以删除内容,但我没有收到此消息 . 这是正确的还是我做错了什么?解决这个问题的正确方法是什么?

16 回答

  • -10

    我遇到过同样的问题 . 我的问题是我的控制器正在返回状态代码而不是JSON . 确保您的控制器返回如下内容:

    public JsonResult ActionName(){
       // Your code
       return Json(new { });
    }
    
  • 12

    我估计你的aspx页面不会返回JSON对象 . 你的页面应该做这样的事情(page_load)

    var jSon = new JavaScriptSerializer();
    var OutPut = jSon.Serialize(<your object>);
    
    Response.Write(OutPut);
    

    另外,尝试更改AjaxFailed:

    function AjaxFailed (XMLHttpRequest, textStatus) {
    
    }
    

    textStatus 应该为您提供所获得的错误类型 .

  • 26

    jQuery.ajax尝试根据指定的 dataType 参数或服务器发送的 Content-Type 标头转换响应正文 . 如果转换失败(例如,如果JSON / XML无效),则会触发错误回调 .


    您的AJAX代码包含:

    dataType: "json"
    

    在这种情况下jQuery:

    将响应评估为JSON并返回JavaScript对象 . [...] JSON数据以严格的方式解析;任何格式错误的JSON都会被拒绝,并抛出一个解析错误 . [...]空的回应也被拒绝;服务器应该返回null或{}的响应 .

    您的服务器端代码返回带有 200 OK 状态的HTML代码段 . jQuery期待有效的JSON,因此会触发抱怨 parseerror 的错误回调 .

    解决方案是从jQuery代码中删除 dataType 参数并返回服务器端代码:

    Content-Type: application/javascript
    
    alert("Record Deleted");
    

    但我宁愿建议返回JSON响应并在成功回调中显示消息:

    Content-Type: application/json
    
    {"message": "Record deleted"}
    
  • 0

    使用以下代码确保响应采用JSON格式(PHP版本)...

    header('Content-Type: application/json');
    echo json_encode($return_vars);
    exit;
    
  • 29

    如果您始终从服务器返回JSON(没有空响应),则 dataType: 'json' 应该有效,并且不需要 contentType . 但是请确保JSON输出...

    jQuery AJAX将对有效但未反序列化的JSON抛出'parseerror'!

  • 15

    如果实现的Web服务方法无效,则只需从头中删除 dataType: 'json' .

    在这种情况下,Ajax调用不希望具有JSON返回数据类型 .

  • 11

    您只需删除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
    });
    
  • 5

    我有同样的问题 . 这是因为我的JSON响应包含一些特殊字符,并且服务器文件未使用UTF-8编码,因此Ajax调用认为这不是有效的JSON响应 .

  • 3

    您的脚本需要以JSON数据类型返回 .

    试试这个:

    private string test() {
      JavaScriptSerializer js = new JavaScriptSerializer();
     return js.Serialize("hello world");
    }
    
  • 1

    See this . 它也有类似的问题 . 工作我试过 .

    不要删除 dataType: 'JSON',

    Note: echo only JSON Formate in PHP file if you use only php echo your ajax code return 200

  • 1

    另一件让我烦恼的事情是使用 localhost 而不是127.0.0.1,反之亦然 . 显然,JavaScript无法处理从一个到另一个的请求 .

  • 0

    我有类似的问题,但当我试图删除数据类型:'json'我仍然有问题 . 我的错误是执行而不是成功

    function cmd(){
        var data = JSON.stringify(display1());
        $.ajax({
            type: 'POST',
            url: '/cmd',
            contentType:'application/json; charset=utf-8',
            //dataType:"json",
            data: data,
            success: function(res){
                      console.log('Success in running run_id ajax')
                      //$.ajax({
                       //   type: "GET",
                       //   url: "/runid",
                       //   contentType:"application/json; charset=utf-8",
                       //   dataType:"json",
                       //   data: data,
                       //  success:function display_runid(){}
                      // });
            },
            error: function(req, err){ console.log('my message: ' + err); }
        });
    }
    
  • 0

    我使用多个空格分隔的 dataTypejQuery 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
    });
    
  • -1

    我用更新的jQuery库遇到了这个问题 . 如果服务方法没有返回任何内容,则表示返回类型为 void .

    然后在你的Ajax调用中请提及 dataType='text' .

    它将解决问题 .

  • 0

    试试以下

    $.ajax({
        type: 'POST',
        url: 'Jqueryoperation.aspx?Operation=DeleteRow',
        contentType: 'application/json; charset=utf-8',
        data: { "Operation" : "DeleteRow", 
                "TwitterId" : 1 },
        dataType: 'json',
        cache: false,
        success: AjaxSucceeded,
        error: AjaxFailed
    });
    

    要么

    $.ajax({
        type: 'POST',
        url: 'Jqueryoperation.aspx?Operation=DeleteRow&TwitterId=1',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        cache: false,
        success: AjaxSucceeded,
        error: AjaxFailed
    });
    

    在JSON对象中使用双引号而不是单引号 . 我认为这将解决这个问题 .

  • 969

    这只是为了记录,因为我在寻找解决我的问题的方法时碰到了这个帖子,这个问题与OP类似 .

    在我的情况下,由于Chrome中的same-origin policy,我的jQuery Ajax请求无法成功 . 当我修改我的服务器(Node.js)时,所有问题都解决了:

    response.writeHead(200,
              {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "http://localhost:8080"
            });
    

    它花了我一个小时的时间撞到了墙上 . 我感觉很蠢......

相关问题