Mol*_*lod 1 php ajax wordpress jquery json
尝试通过ajax请求获取json数据,但始终收到此错误:
Uncaught SyntaxError Unexpected Number
Run Code Online (Sandbox Code Playgroud)
这是我的js代码:
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: { action : 'getPills' },
success: function(data){
product = JSON.parse(data);
console.log(product);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的PHP代码:
add_action('wp_ajax_getPills', 'getPills');
add_action('wp_ajax_nopriv_getPills', 'getPills');
function getPills(){
$data = array(
"test" => 'test'
);
error_log(json_encode($data), 0);
echo json_encode($data);
}
Run Code Online (Sandbox Code Playgroud)
调用error_log以查看我尝试接收的json数据:
{"test":"test"}
Run Code Online (Sandbox Code Playgroud)
我之前在其他项目上使用过ajxa + json,这一切都很好。我不知道如何解决它:(
找到了解决方案。
我需要die()在AJAX处理程序函数的末尾添加以防止进一步的内容。Wordpress 0在响应末尾添加。像这样:
{"test":"test"}0
Run Code Online (Sandbox Code Playgroud)
因此在AJAX处理程序函数末尾的die()解决了该问题