是的,您可以嵌套 ajax 回调。但首先我们可能想回顾一下我们在这里讨论的内容。
JSON
代表javascript object notation
。它不是一种数据类型,而是一种将 javascript 对象编码为文本字符串的方法,以便可以轻松存储/传输。https://www.w3schools.com/js/js_json_intro.asp https://www.w3schools.com/js/js_json_intro.asp
jQuery
是一个javascript库。它基本上是普通 JavaScript 的语法糖。https://jquery.com/ https://jquery.com/
PHP
是一种服务器端语言,用于接收客户端请求、处理请求并返回响应。您不从客户端调用 php 函数。您提出请求,服务器决定如何响应。https://www.php.net/ https://www.php.net/
顺便说一下,如果您希望从同一 URL 返回不同的数据,则必须将其添加到选项对象中,然后处理该服务器端。客户端会是这样的:
jQuery.post(my_ajax.ajax_url, { action: 'myphp', return_type: 'string' })
.done(function(data) { //data will be a string
jQuery('#adivID').html(data);
//this part doesn't make sense, because if the data is a string,
//it won't have an 'id' property. But maybe in your actual code this
//does make sense. So this is just an example of how nesting works.
jQuery.getJSON(my_ajax.ajax_url, { ids: data.ids, return_type: 'json' })
.done(function(json) { //json will be an object
//do stuff with the object
})
.fail(function() {
//response was probably not properly json formatted
});
})
.fail(function(xhr, status, error) {
console.log(xhr.responseText);
alert(error);
});
jQuery.post() https://api.jquery.com/jquery.post/ and jQuery.getJSON() https://api.jquery.com/jquery.getjson/只是短手jQuery.ajax() https://api.jquery.com/jquery.post/,因为它们需要更少的参数,并且除非您正在做更复杂的事情,否则会使您的代码更具可读性。
编辑(因为您添加了 php 代码):
我对 wordpress 不熟悉,需要读几遍才能尝试弄清楚你的代码在做什么。但我从docs https://developer.wordpress.org/reference/classes/wpdb/,你可能想要这样的东西:
$ids = $wpdb->get_results("SELECT id FROM mycats", ARRAY_N); //returns an indexed array of ids
switch($_POST["return_type"]) {
case "string": //returns a comma separated string of ids
echo implode(", ", $ids);
break;
case "json": //returns a json array of ids
echo json_encode($ids);
break;
}
但话又说回来,getJSON()
将会失败,因为post()
将返回一个字符串。如果不确切知道您想要实现什么目标,就很难提出代码建议。可能还值得注意的是,在 php 中object https://www.php.net/manual/en/language.types.object.php不同于关联数组 https://www.w3schools.com/php/php_arrays_associative.asp不同于索引数组 https://www.w3schools.com/php/php_arrays_indexed.asp。此外,所有变量都以$
. wpdb
!= $wpdb
如果你没有因此而损失几个小时,那么你的 php 还没有写够,哈哈。