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

时间:2011-05-31 11:17:38

标签: javascript jquery asp.net ajax json

我已经在我的网站上实现了Ajax请求,我正在从网页上调用端点。它总是返回 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);
}

JqueryOpeartion.aspx

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

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

16 个答案:

答案 0 :(得分:1020)

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"}

答案 1 :(得分:30)

我使用多个空格分隔的dataType s(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
});

答案 2 :(得分: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
});

答案 3 :(得分:19)

这只是为了记录,因为我在寻找解决问题的方法时碰到了这篇文章,这与OP的相似。

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

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

我花了一个小时的时间把头撞在墙上。我感觉很蠢......

答案 4 :(得分:13)

我认为你的aspx页面没有返回JSON对象。 你的页面应该做这样的事情(page_load)

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

Response.Write(OutPut);

另外,尝试更改AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus应该会为您提供您所遇到的错误类型。

答案 5 :(得分:12)

我在更新的jQuery库中面临这个问题。如果服务方法没有返回任何内容,则意味着返回类型为dataType='text'

然后在您的Ajax电话中,请提及public ActionResult Index() { var DataContext = new EditProfileFormFieldsDataContext(); return View("EditProfile", DataContext.Controls.ToList()); }

它将解决问题。

答案 6 :(得分:7)

如果您实施的Web服务方法无效,则只需从标题中删除dataType: 'json'

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

答案 7 :(得分:4)

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

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

答案 8 :(得分:3)

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

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

答案 9 :(得分:3)

我有类似的问题,但当我尝试删除数据类型时:&#39; json&#39; 我还有问题。 我的错误是执行而不是成功

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

答案 10 :(得分:2)

让我感到困惑的另一件事是使用localhost而不是127.0.0.1,反之亦然。显然,JavaScript无法处理从一个到另一个的请求。

答案 11 :(得分:2)

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

不要删除dataType: 'JSON',

注意:如果你只使用php echo你的ajax代码返回200

,那么在PHP文件中只回显JSON Formate

答案 12 :(得分:1)

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

答案 13 :(得分:1)

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

jQuery AJAX将在有效但未序列化的JSON上抛出“ parseerror”!

答案 14 :(得分:-1)

您的脚本要求以JSON数据类型返回。

试试这个:

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

答案 15 :(得分:-10)

尝试以下

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

OR

$.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对象中使用双引号而不是单引号。我认为这将解决问题。

相关问题