javascript - 在 AJAX 中获取 JSON 编码值
问题描述
我正在从数据库中检索数据。当我尝试使用在控制台中输出它时console.log(response)
,我会得到这个:
Array
(
[deptCode] => Econ
[collegeCode] => BA
[deptName] => Economics
)
我期待得到值Econ, BA, and Economics
。
我的问题是当我使用 将它从 PHP 传递到 AJAX 时response["deptCode"]
,我会得到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]);
}
但结果是这样的: 来自控制台的图像结果
这是我的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;
动作.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]);
//}
}
})
})
任何帮助,将不胜感激 :)
解决方案
我json_decode
之前有过这样的错误。要在 ajax 响应中解析为 JSON,您必须在 PHP 中解码数据。即请json_decode
在 PHP 中使用。然后JSON.parse(response)
在ajax响应中。我希望你能解决它。
推荐阅读
- google-bigquery - 从结果表中删除不相关的数据 - 已编辑
- sql - Athena SQL 中的正确案例
- android - 回退到 @StringRes 的 Android 数据绑定 String 的 TextView 值
- javascript - 通过 $ 变量 javascript/html 的 href
- qt - 使用 Qt 更改按钮大小运行时
- javascript - 数据表操作自定义删除确认不起作用
- swift - ios swift 使用云MQTT
- python - Argparse:选项要求的例外= True
- javascript - 重置 `!important` CSS 并允许使用 JS 进行样式设置
- reactjs - 我正在使用 React,我想为网格中元素的重新定位设置动画。如何集成 GSAP 以自动重新定位?