PHP无法从ajax调用中检索JSON

时间:2016-11-17 13:11:16

标签: jquery json ajax post

这是我的JS代码:

var person = [];
    person[0] = "John";
    person[1] = "Doe";
    person[2] = 46;
    var myData = JSON.stringify(person);
    $.ajax({
        type: "POST",   
        url: "test.php",
        dataType : "text", 
        contentType: "application/json; charset=utf-8",
        data: myData,
        success: function(answer) {
            alert(answer);
        },
        complete: function() {
        },
        error: function(jqXHR, errorText, errorThrown) {
            alert(jqXHR+" - "+errorText+" - "+errorThrown);
        }
    });

这是php:

if(isset($_POST['myData']))
{
 echo "ok";
}
else
{
 echo "not_ok";
}
?>

它总是返回“not_ok”。为什么我的PHP代码无法检索JSON?我做错了什么?有人能解释一下吗?

3 个答案:

答案 0 :(得分:1)

尝试以下

dataType : "json":告诉jQuery你希望它解析返回的JSON

json_encode():PHP函数以json格式编码数组。

<强>的JavaScript

var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;

$.ajax({
    type: "POST",   
    url: "test.php",
    dataType : "json",  // Set datatype json
    data: {myData : person}, // Request Parameters
    success: function(answer) {
        console.log(answer); // JSON Response
    },
    complete: function() {
    },
    error: function(jqXHR, errorText, errorThrown) {
        alert(jqXHR+" - "+errorText+" - "+errorThrown);
    }
});

<强> PHP

<?php
    if(isset($_POST['myData'])){
        $status = "ok";
    }
    else
    {
        $status = "Not Ok";
    }
    echo json_encode(array("status" => $status));
    exit;
?>

<强>输出

Object {status: "ok"}

答案 1 :(得分:0)

您需要一些密钥才能从post / get变量中获取数据

 data:{firstname:"John",lastname:"Doe",age:45},

PHP:

$_POST['firstname']

data:{data:["John","Doe",45]},

如果你真的想要一个数组

 $_POST['data']

答案 2 :(得分:0)

您正在将数组转换为json格式的字符串,而不使用任何名称。但你可以在ajax帖子中发布数组,你不需要对其进行字符串化。 您可以按原样传递数组

data: {myData: person},



var person = [];
    person[0] = "John";
    person[1] = "Doe";
    person[2] = 46;

$.ajax({
    type: "POST",   
    url: "test.php",
    dataType : "text", 
    contentType: "application/json; charset=utf-8",
    data: {myData: person},
    success: function(answer) {
        alert(answer);
    },
    complete: function() {
    },
    error: function(jqXHR, errorText, errorThrown) {
        alert(jqXHR+" - "+errorText+" - "+errorThrown);
    }
});