我试图解析一个字符串到jquery对象,但我没有得到它在正确的格式。不知道错误在哪里。
我的目标是从数据库加载数据的把它变成一个对话框,在这里我可以更新用户我如何正确使用json和jQuery之间的交互jQuery
我在我的js文件中的POST请求时执行按下一个按钮:
$.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抛出从数据库返回的加载的字符串:2
我分析了串
$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;
}
编辑js文件中的响应我发现字符串gehts \ 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
现在,它会很高兴地知道为什么我得到这些新的生产线,甚至当我不回应任何事情
但我认为这并不适合头部querstion
提示:请勿尝试手动生成JSON。使用内置的语言功能。 – 2014-09-05 13:57:39
@ʰᵈˑ那种无用的提示,因为他在php中使用了json_encode。其他的东西只是测试数据,他把它放在 – Pinoniq 2014-09-05 13:58:20
第1行的jQuery文件 - 看起来像他正在用手建造它... – 2014-09-05 13:58:52