本文介绍了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