如何使用json在jquery和php之间正确交互

时间:2014-09-05 13:55:33

标签: php jquery json

我尝试将字符串解析为jquery对象,但我没有以正确的格式获取它。不知道错误在哪里。 我的目标是从数据库加载数据并将其放入对话框中,我可以在其中更新用户

我的js文件中有一个帖子请求,按下按钮执行:

$.post("index.php", { "id": ID , "action": "edit_row"},
    function(input){
        console.log(input); //{"id":"1","fname":"Test","lname":"Name"}
        console.log(input.id); //undefined
        var data = $.parseJSON(input); //Uncaught SyntaxError: Unexpected token
        console.log(data); //not possible
        console.log(data.id); //not possible
        test = {"id":"1","fname":"Test","lname":"Name"};
        console.log(test); // I get the object
        console.log(test.id); //1
    }); // when I use ',"json"' between the brackets nothing happens, no logs are written in console

我的index.php抛出从数据库加载的字符串:

$query = "SELECT `id`, `fname` , `lname` FROM `user` WHERE `id`= ".$id; //it's just one row
$result = sql_query($query);

    while ($row= mysql_fetch_assoc($result)){
            $data = $row;
    };
echo json_encode($data);

//php function
function sql_query($query){

$result = mysql_query($query);
if(!$result) {
    die("Request Failed: " . mysql_error());
}   
   return $result;
}

编辑2

我分析了js文件中的字符串响应我发现字符串格式为\ r \ n \ r \ n \ r \ n到最后。即使我没有回复php文件中的任何内容......

我认为在处理ajax请求时,我的index.php中存在某些损坏。

我在不同的php文件上做了请求,并且没有任何问题。

$.post("test.php", { "id": ID , "action": "edit_row"},
    function(input){
        console.log(input); // I get the object
        console.log(input.id); //1
        //testdata below
        test = {"id":"1","fname":"Test","lname":"Name"};
        console.log(test); // I get the object
        console.log(test.id); //1
    },"json");  //using ',"json"' is working on the test.php file now

现在很高兴知道为什么即使我没有回复任何内容我也会获得这些新行

但我认为这不适合头部问题

1 个答案:

答案 0 :(得分:1)

在index.php页面上使用此语句

<?php error_reporting(0); ?>

由于您使用的是mysql_query,因此会为不推荐使用的函数提供警告消息,从而导致错误。整个警告消息将返回到您的页面,该页面不是您期望的格式。该声明将取消警告,应该没问题。但我建议你使用PDO或mysqli。

相关问题