Ajax Multi Response Problem

时间:2020-04-14 作者:CristianR

当我试图从php shortcode函数获得多个响应时,其Json输出结果很奇怪。在我的php中,

$result[\'success\']=false;
$result[\'string\']=\'You have not uploaded project file, please upload first!\';
echo json_encode($result);
在js文件中

$.post(ajax_object.ajax_url, {         //POST request
      ...............
    }, function(data) {                //callback
        console.log(data);
        alert(data);  
});
但在我的结果中,我得到了

{"success":"true","string":"You have not uploaded project file, please upload first!"}0

我不知道为什么我在结果后面得到了数字0。

1 个回复
SO网友:Jacob Peattie

如中所述the documentation:

当处理程序完成所有任务时,它需要死亡。如果您正在使用WP_Ajax_Response 或wp\\u send\\u json*函数,这将自动为您处理。如果没有,只需使用WordPresswp_die() 作用

wp_die();
// That\'s all folks!
因此,您需要使用:

$result[\'success\'] = false;
$result[\'string\']  = \'You have not uploaded project file, please upload first!\';
echo json_encode( $result );
wp_die();

$result[\'success\'] = false;
$result[\'string\']  = \'You have not uploaded project file, please upload first!\';
wp_send_json( $result );
您还可以使用success 属性设置为false 对于您这样的人:

$result = \'You have not uploaded project file, please upload first!\';
wp_send_json_error( $result, 400 );
这将导致如下结果:

{
    "success": false,
    "data": "You have not uploaded project file, please upload first!"
}

相关推荐

400个错误请求进入AJAX调用

我尝试,当单击submit按钮时,用一些值传递ajax请求,然后计算这些值并返回。My Problem : 当我进行自定义Ajax调用时,我从管理Ajax得到400个错误。php。请帮我找出我的错误或最好的方法来做这件事。Ajax Call - footer.php(theme footer) <script> $(function() { $(\"#calc_form\").on(\"submit\", function(e) {