Ajax错误:即使请求状态为200,也会调用函数

时间:2017-07-11 07:04:59

标签: jquery ajax

这是我的Ajax呼叫代码:

var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
    type: 'POST',
    url: 'ajax.php',
    cache: false,
    data: { json : JSON.stringify({
        name:name,
        email:email,
        password:password
    })},
    dataType: 'json',

    success: function(){
        alert('request successful');
    },

    error: function(){
        alert('error occured');
    }

});

请求状态为200,但始终调用错误函数。

有谁知道,

  • 为什么会这样?
  • 我该如何解决?

1 个答案:

答案 0 :(得分:2)

最有可能的问题是这一行:dataType: 'json',因为它期待Json响应并且您正在发送html或文本文本响应。我们先来看看定义

  • JSON.stringify 将Javascript对象转换为JSON文本,并将该JSON文本存储在字符串中。

  • contentType 是发送到服务器的标头,指定特定格式。

  • dataType 你告诉jQuery期待什么样的回应。

<强>示例:

如果您发布的内容如下:{"name":"John Doe"}并期待回复:{"success":true}

然后你应该:

var data = {"name":"John Doe"};
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),

更多详情:Check jQuery Docs

解决方案1:(已测试)

  • 只需删除dataType: 'json',行,让jQuery决定数据类型。 (它在识别方面做得非常好)或确保在双方(客户端和服务器)上使用正确的dataType

解决方案2:(已测试)

<强> jQuery的:

var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
    type: 'POST',
    url: 'ajax.php',
    dataType : "html", //assuming you need html response like '<div>Success</div>'
                       //Common types: html, xml, json & text
    cache: false,
    data: { json : encodeURIComponent(JSON.stringify({
        name:name,
        email:email,
        password:password
    }))},


    success: function(){
        alert('request successful');
    },

    error: function(){
        alert('error occured');
    }

});

<强> PHP:

$json_data = json_decode(urldecode($_POST['json']));
//now $json_data variable has decoded JSON data 
echo $json_data->name;

解决方案3:(未经测试)

通过设置contentType

发送JSON对象

contentType: "application/json; charset=utf-8", 

然后使用php://input阅读原始输入(注意:$ _POST在这里工作)

以下是如何:

  • 在PHP文件header('Content-Type: application/json; charset=UTF8');
  • 中设置内容类型
  • 获取数据$input = file_get_contents('php://input');
  • 解码数据$decoded_input = urldecode($input);
  • 最后,将其解码为JSON对象$data = json_decode($input);
相关问题