我正在使用jQuery的$.post函数从php文件中检索一些数据,但返回的数据似乎没有显示?这是我得到的。
Javascript 代码:
$(document).ready(function(){
$("#import").click(function(){
//This code works when uncommented, used for debugging.
/*var x = "tester";
$('input[name=title]').val(x);*/
$.post("import.php", function(data){
$('input[name=title]').empty().val(data.name); // John
$('input[name=subtitle]').empty().val(data.time); // 2pm
}, "json");
});
});
PHP 导入.php代码:
<?php
$my_array = array("name"=>"John","time"=>"2pm");
echo json_encode($my_array);
?>
是我错过了什么愚蠢的事情,还是我做错了。我对javascript/jquery相当陌生。
你必须使用json.parse()并将其分配给一个变量以将其用作对象。
从这里下载 JSON2.js
json.parse 有这个文档。
JSON 的请求类型并不意味着 AJAX 函数将"data"值作为对象返回。 它仍然是一个字符串,需要解析
var myObject = JSON.parse(data);
然后你可以像这样使用它
alert(myObject.name);