本文介绍了Ajax调用触发错误事件但返回200 ok的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$.ajax({
        url: 'http://intern-dev01:50231/api/language',
        type: 'GET',
        dataType: 'json',
        success: function() {
            console.log('It Works!');
        },
        error: function (request,status, error) {
            console.log(error);
            alert(status);
        }
    });

为什么这个ajax调用不起作用?如果我在浏览器中调用它可以正常工作:/。

Why do this ajax call not work ?? if i call in browser it works fine :/.

这就是fiddler返回的内容:

This is what fiddler returns:

HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 26 Apr 2013 06:56:40 GMT

[{"LanguageId":1,"LanguageName":"Dansk"},{"LanguageId":2,"LanguageName":"Tysk"},{"LanguageId":3,"LanguageName":"Engelsk"}]


推荐答案

如果ajax响应有效,则必须检查它。在ajax中指定时:

You have to check ajax response if it is valid or not. When you specify in ajax:

dataType: 'json',

如果响应无法解析为JSON,jQuery将触发错误事件,即使服务器返回200 OK。检查从服务器返回的数据,并确保它是有效的JSON(尝试JSONLint服务)。

jQuery will fire the error event if the response cannot be parsed as JSON, even if server returns 200 OK. Check the data returned from the server and make sure it is valid JSON (try JSONLint service).

如果返回的数据不是JSON或它有语法错误,那么修复它们在您的服务器端代码中。你可以从服务器端脚本返回{}。

If the returned data is not JSON or it has syntax errors then fix them in your server side code. You can just return {} from the server side script.

也试试这个。

$.ajax({
    url: 'http://intern-dev01:50231/api/language',
    type: 'GET',
    cache: false,
    complete: function (xhr, status) {
      if (status === 'error' || !xhr.responseText) {
          console.log(error);
          alert(status);
      }
      else {
       console.log('It Works!');.
      }
    }
});

这篇关于Ajax调用触发错误事件但返回200 ok的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:09
查看更多