我正在从数据库中检索数据。当我尝试使用console.log(response)
在控制台中将其输出时,我将得到以下信息:
Array
(
[deptCode] => Econ
[collegeCode] => BA
[deptName] => Economics
)
我期望得到值Econ, BA, and Economics
。
我的问题是,当我使用response["deptCode"]
将它从PHP传递到ajax时,我会得到undefined
。
我尝试做data = JSON.parse(response);
,但会收到错误:
Uncaught SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
我也尝试过:
for(var key in response){
console.log(response[key]);
}
但是结果是这样的:image result from console
这是我的db.php:
public function getDept($code){
$sql = 'SELECT * FROM department WHERE "deptCode" = :code';
$stmt = $this->conn->prepare($sql);
$stmt->execute(['code'=>$code]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
action.php:
if(isset($_POST['edit_id'])){
$id = $_POST['edit_id'];
$row = $db->getDept($id);
echo json_encode($row);
}
索引:
$("body").on("click", ".editBtn", function(e){
e.preventDefault();
edit_id = $(this).attr('id');
$.ajax({
url: "action.php",
type: "POST",
data:{edit_it:edit_id},
success:function(response){
console.log(response);
//data = JSON.parse(response);
//for(var key in response){
// console.log(response[key]);
//}
}
})
})
任何帮助将不胜感激:)