我只想从这个数组中检索值。我尝试过
data[0].title
但不起作用。
$.ajax({
type: "POST",
url: 'videos_load.php',
data: filters,
success: function(data) {
console.log(data.title);
console.log(data);
}
});
输出:
未定义
[{
"id": "1",
"title": "Fast whoosh sound effect",
"Video": "Fast Whoosh Sound Effect.mp4",
"links": "0",
"description": null,
"likes": "15",
"dislikes": "5",
"Date": "2022-01-26",
"fliters": null,
"IdUser": "1"
}, {
"id": "2",
"title": "How to replace a green screen background",
"Video": "How to replace a green screen background.mp4",
"links": "0",
"description": "hello everyone hope you enjoy this video ",
"likes": "25",
"dislikes": "16",
"Date": "2024-07-24",
"fliters": "film",
"IdUser": "2"
}, {
"id": "3",
"title": "Transformer green screen effects",
"Video": "Transformer green screen effects.mp4",
"links": "0",
"description": "A transformer on ",
"likes": "5",
"dislikes": "10",
"Date": "2023-10-10",
"fliters": "action",
"IdUser": "2"
}]
问题是您接收到的数据是 JSON 字符串格式,因此您需要将其解析为数组或对象才能直接访问其属性。
修复方法如下:
在成功回调中使用 JSON.parse(data) 解析 JSON 响应。 解析后,您可以正常访问标题和其他属性。 这是修改后的代码:
$.ajax({
type: "POST",
url: 'videos_load.php',
data: filters,
success: function(data) {
const parsedData = JSON.parse(data); // Parse the JSON string
console.log(parsedData[0].title); // Access the title of the first item
console.log(parsedData); // Verify the parsed data
}
});
或者,如果您的服务器已经发送带有正确 Content-Type: application/json 标头的响应,您可以在 AJAX 请求中指定 dataType: "json"。 jQuery 会自动解析响应,您可以直接访问数据,而不需要 JSON.parse。
$.ajax({
type: "POST",
url: 'videos_load.php',
data: filters,
dataType: "json", // Automatically parse JSON
success: function(data) {
console.log(data[0].title); // Access the title of the first item
console.log(data); // Verify the parsed data
}
});
任一方法都允许您按预期访问 data[0].title。