javascript - 重新调整有效 JSON 时调用的 Ajax 错误回调

标签 javascript php ajax json

在我的 js 文件中,我调用以下内容:

    $.ajax({
          type: "POST",
          dataType: "application/json",
          url: "php/parseFunctions.php",
          data: {data:queryObj},
          success: function(response) {
             theFunction(response);
          },
          complete:  function(response) {
             theFunction(response);
          },
          error: function(response) {
             theFunction(response); // response = Object {readyState: 4, responseText: "{"found":0}", status: 200, statusText: "OK"

          }
    });

在我的 php/parseFunctions.php 我有:

$returnResults = array(); 
$returnResults['found']=count($returnResults);  
echo  json_encode($returnResults);
exit;

我希望调用 success 回调,并且 response 是 json 对象 {"found":"0"}

相反,error 回调被调用并且 response = Object {readyState: 4, responseText: "{"found":"0"}", status: 200, statusText: "好”

我读到如果返回的 JSON 无效,就会发生这种情况,但我不觉得是这样。

我做错了什么?

最佳答案

我认为问题出在您的 dataType 属性上。您已将其设置为 "application/json"。虽然这是一个值 mimeType 值,但 $.ajax 函数需要以下预定义值之一:xml、json、script 或 html,如 the relevant page of the documentation 中所列。 .

尝试让您对 $.ajax 的调用看起来像这样:

$.ajax({
      type: "POST",
      dataType: "json",
      url: "php/parseFunctions.php",
      data: {data:queryObj},
      success:{...},
      complete:{...},
      error:{...}
});

关于javascript - 重新调整有效 JSON 时调用的 Ajax 错误回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904300/

相关文章:

javascript - 同步时排除模型属性 (Backbone.js)

javascript - 声明和获取 js 对象的最佳方法是什么? (图案)

php - symfony2 : how to access service from template

Javascript 依赖项未通过 Ajax 加载

javascript - 如何在Chrome开发者工具中解析console.log?

javascript - 为什么只有当它们是变量时,React 才会将 undefined/boolean/null 解析为字符串?

php - PHP 中的段错误,使用 SOAP 连接到 SalesForce

javascript - 当我使用 ajax 从 "echo"PHP 获取 html 代码时,我需要继续执行 JS 代码

jQuery getScript() 有时工作正常,有时返回 "parsererror"和 TypeError 异常

javascript - JqueryUI 自动完成,自定义 renderItem 不起作用