post.js
$.post(
"/scripts/update.php",
{id: testId, age: testAge},
function(data) {
$(".testDiv").html(data.testId);
$(".testDiv2").html(data.testAge);
},
"json"
);
update.php
$userId = $_POST["id"];
$userAge = $_POST["age"];
// contact database and retrieve user Id and user name...
echo json_encode(array("testId"=>$userId, "testAge"=>$userAge));
如果我要取出, "json");
代码,我可以很好地将信息传递给update.php
,但无法检索任何数据。添加 json 后,我无法检索或发送数据...
我做错了什么?
我认为 $.ajax 函数更适合您的需求:
$.ajax({
type: "POST",
url: "/scripts/update.php",
data: {id: testId, age: testAge},
dataType: "json",
success: function(data) {
$(".testDiv").html(data['testId']);
$(".testDiv2").html(data['testAge']);
}
});
你的PHP脚本将保持不变。我提供代码是因为您几乎没有提供有关您收到的错误的信息。正如加缪所说,请提供有关错误的更多信息。
如果你正在访问data.testId
,这意味着你正在访问你从更新中收到的响应(存储在你的示例中称为data的变量中.php作为你的jQuery后调用的结果。通过将数据类型提及为 jSon
,您可以确保来自服务器的响应将转换为 jSon 格式。
如果您的更新.php页面返回这样的jSon
。{ "id": "3","age":"53"}
然后,您可以访问单独的值,例如 data.id
和 data.age
.
如果您有一个有效的 json 从服务器页面返回,则下面的代码应该可以工作,如上
$.post("/scripts/update.php", { id: testId, age: testAge}, dataType:"json",function(data) {
$(.testDiv).html(data.id);
});
我会按照@gimg1说的去做,但像这样:
var form_data = {
testId: $("#testIdForm").val(),
testAge: $("#testAgeForm").val()
};
$.ajax({
type: "POST",
url: "/scripts/update.php",
data: {id: testId, age: testAge},
dataType: form_data,
success: function(response) {
if(response == 'success'){
//do success function here
}
}
});