这是我的函数.php包含以下代码的脚本。数组被编码为 JSON。
函数.php
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
我的global.js有以下代码,它在jQuery中发出AJAX请求:
$.ajax({
type: "POST",
url: "functions.php", // file to reach Ajax call
dataType: "json",
data: {
action: 'custom',
id: id,
},
success:
function(data) {
setCustom(data.custom);
我想知道data
包含什么function(data)
?setCustom(data.custom)
,这是什么意思?有人可以给我解释一下吗?
数据包含服务器端 json_encode() 提供的对象文字。它已被自动解析,因为数据类型设置为 json。
例:
.PHP:
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
将给出以下 json 字符串(格式化以便更好地理解):
{
"custom": {
"main":[
{
"symbol":"MAP4",
"official_ID":"112315"
}
]
}
}
上面的 ajax 调用设置为数据类型 json。 jQuery 知道是否设置了此数据类型,它会自动将字符串解析为对象文字。
Javascript:
$.ajax({
type: "POST",
url: "url.php", // file to reach Ajax call
dataType: "json",
success: function(data) {
var main = data.custom;
console.log(main); // returns the child object with "main"
}
});
data 包含初始对象,custom 是数据的子对象,main 是 custom 的子对象。
成功:请求成功时要调用的函数。该函数传递三个参数:
- 从服务器返回的数据
- 地位
- jqXHR (XMLHttpRequest Object)
在您的 PHP 代码中,您添加了echo json_encode($final);
如果请求成功完成,将返回该代码。响应将传递给data
稍后可以在前端代码中使用。
您可以在 http://api.jquery.com/jQuery.ajax/阅读有关$.ajax()
的更多信息