我一直试图从php检索json数据。我有一个HTML表打开一个模态。我通过ajax post传递行中数据的id,在php文件中,我计划使用传递的id在数据库中查找相关行,并返回所有要在模态中显示的信息。目前我一直在尝试返回id和一些临时值。
Javascript: var id = recipient;
console.log("id: " + id);
var idObject = { id: id }
$.ajax({
url: "json.php",
type: "POST",
data: idObject,
dataType: "json",
contentType: "application/json"
})
json.php:
<?php
$id = $_POST["id"];
$firstName = "firstname";
$lastName = "lastname";
$email = "email@hotmail.co.uk";
if(isset($id)){
$data = array(
"id" => $id,
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email
);
echo json_encode($data);
}
?>
我尝试使用success来调用一个函数,但没有任何运气。谁能告诉我正确的方向?
试试这个:
$.ajax({
url: "json.php",
type: "POST",
data: {id: id},
dataType: "json",
contentType: "application/json"
}).success(function(data){
//data is now a JSON object containing data
//you outputted from PHP, example:
$('#form-email').val(data.email);
});
也考虑使用HTTP状态码或在JSON中返回status
字段,即使没有设置$id
,所以你有一致的响应。
示例(使用PHP 5.4+
短数组语法):
if(isset($id))
{
return json_encode([
'status' => 'ok',
'errors' => [],
//(rest of data)
]);
}
else
{
return json_encode([
'status' => 'error',
'errors' => ['no id given'],
]);
}