我正在使用 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 import.php代码:
<?php
$my_array = array("name"=>"John","time"=>"2pm");
echo json_encode($my_array);
?>
我是否遗漏了一些愚蠢的事情,或者我是否错误地处理了这件事。我是 javascript/jquery 的新手。
最佳答案
您必须使用 json.parse() 并将其分配给变量才能将其用作对象。
从 here 下载 json2.js
json.parse 有 this文档。
请求类型为 JSON 并不意味着 ajax 函数将“数据”值作为对象返回。它仍然是一个字符串,需要用
进行解析var myObject = JSON.parse(data);
然后你就可以像这样使用了
alert(myObject.name);
关于php - jQuery $.post() 函数难以不显示结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111567/