我有下表:
| id | name | age |
|----|-------|-----|
| 1 | Peter | 23 |
| 2 | Amie | 34 |
| 3 | Eddy | 45 |
| 4 | Peter | 56 |
| 5 | Eddy | 67 |
我现在想要检索名为Peter
的所有用户的年龄。
JS:
function getAge() {
$.ajax({
type : "POST",
url : "backend.php",
data : {
q : "user",
name : 'Peter'
},
success : function(data) {
console.log(data)
if (data.length > 0) {
} else {
console.log("empty")
}
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
PHP:
if (isset ( $_POST )) {
if ($_POST ['q'] == "user") {
$name = $_POST ["name"];
$stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );
$stmt->bind_param ( "s", $name );
$stmt->execute ();
$stmt->store_result ();
if ($stmt->num_rows >= 1) {
echo "Yes"; // only this Yes is being returned
$arr = array ();
while ( $stmt->fetch () ) {
$arr [] = $name;
}
return $arr;
} else {
echo "0 records found";
}
$link->close ();
}
而不是23
和56
的数组,我只获得Yes
。
那么如何才能获得具有年龄的数组呢?
答案 0 :(得分:1)
只需将此添加到您的php函数中。这意味着你想将json返回到这个页面
header('Content-Type: application/json');
将您的返回$ arr更改为echo json_encode($ arr);将数组转换为json对象也会删除回声"是&#34 ;;
echo json_encode($arr);
你的php函数看起来像这样
if (isset ( $_POST )) {
if ($_POST ['q'] == "user") {
header('Content-Type: application/json');
$name = $_POST ["name"];
$stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );
$stmt->bind_param ( "s", $name );
$stmt->execute ();
$stmt->store_result ();
if ($stmt->num_rows >= 1) {
$arr = array ();
while ( $stmt->fetch () ) {
$arr [] = $name;
}
echo json_encode($arr);
} else {
echo "0 records found";
}
$link->close ();
}
}