我在wordpress中使用ajax来获取函数的输出:
jQuery.ajax({
type: "POST",
url:"wp-admin/admin-ajax.php",
data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
success:function(results){
jQuery(".semester_selection").empty();
jQuery(".semester_selection").prop('disabled', false);
jQuery(".semester_selection").append(results);
}
})
这是我使用的功能:
function nafham_list_cats_selection() {
if(isset($_POST['selection_id'])){
nafham_get_listed_cats($_POST['selection_id']);
die();
}
}
使用jQuery ajax我能够得到函数的输出,但我需要做的是获得多个输出,如果函数echos两个变量,我希望能够使用两个值分隔在ajax响应中,这可能吗?
答案 0 :(得分:4)
创建一个输出数组,例如,如果你的php文件中有
// Some code here and finally you've an array to echo/send to the browser i.e.
$data=array("id"=>1, "text"=>"This is some content"); // This is your data array/result
echo json_encode($data); // use json_encode to convert it to json encoded string
上面的代码会将以下json编码的字符串发送到浏览器
{"id":1,"text":"This is some content"}
在你的ajax成功回调函数中你可以使用'parseJSON'将它转换为json对象
jQuery.ajax({
type: "POST",
url:"wp-admin/admin-ajax.php",
data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
success:function(results){
var obj=$.parseJSON(results); // now obj is a json object
alert(obj.id); // will alert "1"
alert(obj.text); // will alert "This is some content"
}
});