我一直在用头撞电脑,试图弄清楚这一点。我的AJAX调用/请求在Chrome中返回正确的对象,但在Firefox/IE8中返回null。我试着将函数分解为一个简单的数组,其中只有一个值/键对,但我仍然收到相同的结果。非常感谢您的任何建议!
简化的PHP函数:
add_action('wp_ajax_get_ldap', 'get_ldap_attr');
add_action('wp_ajax_nopriv_get_ldap', 'get_ldap_attr');
function get_ldap_attr() {
header("Content-Type: application/json", true);
echo json_encode( array("happy" => "coding") );
die();
}
jQuery:
jQuery(function() {
jQuery('#empLanId').on('blur', function () {
var lan = jQuery('#empLanId').val();
var data = { action:"get_ldap", lan:lan };
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
}
您必须在JSON响应中发送正确的内容类型。
// Send as JSON
header("Content-Type: application/json", true);
更新后的功能应该如下所示:
function get_ldap_attr() {
header("Content-Type: application/json", true);
echo json_encode( array("happy" => "coding") );
die();
}
请参阅我之前的答案:
dataType json的jQuery$.ajax请求不会从PHP脚本中检索数据