使用ajax从php多次返回

时间:2015-06-01 19:16:53

标签: php jquery mysql ajax

我想从我的php文件中获得超过1的值。

这是我的ajax代码

$.ajax({
    type: "POST",
    url: "insert.php",
    data: $(this).serialize(),
    success: function(response){
        alert(response);
        alert(response.dummy_code);
        alert(response.user_id);
    },
});

在我的insert.php上我做了这个输出

echo json_encode(array("dummy_code" => "$dummy_code", "user_id" => "$insertet_user_id"));

例如,$dummy_code必须将值5s8374m9f9f3m34mc334$user_id14

使用命令

alert(response);

我得到了这个输出

{"dummy_code":"5s8374m9f9f3m34mc334","user_id":"14"}

另外两个命令的输出

undefined

为什么response.dummy_code& respone.id不工作?

3 个答案:

答案 0 :(得分:3)

因为你要回来一个字符串,你必须parse the string as JSON

function(response){
    var myJSON = JSON.parse(response);
    console.log(response);
    console.log(myJSON.dummy_code);
    console.log(myJSON.user_id);
},

如果您不想这样做,只需向jQuery AJAX request添加dataType -

$.ajax({
    type: "POST",
    url: "insert.php",
    data: $(this).serialize(),
    dataType: 'JSON',

Quit using alert() for troubleshooting.,请改用console.log()

答案 1 :(得分:2)

您是否在响应标头中设置了正确的内容类型?如果不是在echo之前添加这一行:

header('Content-Type: application/json');
echo json_encode(array("dummy_code" => "$dummy_code", "user_id" => "$insertet_user_id"));

答案 2 :(得分:1)

你的响应没有被解析成一个对象只是一个字符串,如果你要返回JSON,告诉jQuery它会为你解析它。
有两种方法,1:将响应类型设置为application/json

header('Content-Type: application/json');

或将$ .ajax中的dataType设置为json

dataType: 'json',