我在元框中进行 ajax 调用并返回一些非常简单的数据。但是,它不断抛出错误:
parsererror
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
这是 ajax 调用:
uid = new Date().getTime();
appReq = jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'admin-ajax.php',
data : { action : 'get_app_sidebars', post_id : currentApp, uid : uid }
});
appReq.done(function(data){
if(data.widgetNum > 0 && data.widgetName != '' && data.widgetBase != '') {
alert(data);
}
else {
// do something here
}
});
appReq.fail(function(jqXHR, textStatus, errorThrown){
alert(textStatus + '\n' + errorThrown);
});
这是 php:
function get_app_sidebars(){
// get the meta for a custom post type
$meta = $this->get_app_meta($_REQUEST['post_id']);
$result['widgetNum'] = $meta['num_widgets'];
$result['widgetName'] = $meta['widget_name'];
$result['widgetBase'] = $meta['widget_base'];
$result = json_encode($result);
echo $result;
}
当我取回数据时,问题就来了:
{"widgetNum":"6","widgetName":"Custom Sidebars","widgetBase":"my-custom-sidebars"}0
好的,当我在 Firebug 中查看时,末尾的“0”在响应中。这让我抓狂,我无法弄清楚 WTF 在将 JSON 发送到浏览器时会发生什么。如果我修剪 0 并通过 jsonlint 运行它,它就会通过。
最佳答案
我建议使用 wp_send_json_success
,因为它会处理所有事情(json 编码、echo
和 die()
):
function get_app_sidebars()
{
$meta = $this->get_app_meta($_REQUEST['post_id']);
if( $meta )
{
$result['widgetNum'] = $meta['num_widgets'];
$result['widgetName'] = $meta['widget_name'];
$result['widgetBase'] = $meta['widget_base'];
wp_send_json_success( $result );
}
else
}
wp_send_json_error( array(
'error' => 'Custom error message'
));
}
}
此外,使用 check_ajax_referer
进行必要的安全检查.
关于php - WordPress 中的 ajax/json 调用以格式错误的 JSON 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292128/