AJAX变量不发送数据(变量返回“0”不是必需的数据)

时间:2016-10-12 15:09:42

标签: javascript php ajax wordpress

我一直在尝试使用AJAX从JS文件发送变量并在Wordpress中触发PHP文件。该函数连接到PHP文件,但它发送的变量存储值“0”。我尝试了很多解决方案,但我不能完全解决这个问题。 JS代码如下:

function data_transfer(){


alert(calc_price);




jQuery.ajax({
    url: '/wp-admin/admin-ajax.php',
    type: 'POST',
    action: 'data_sender',
    data: 
        ({result: calc_price}),
    dataType: 'json',
    cache: false,
    success:function(calc_price){
        alert(calc_price);

},
error: function(jqXHR,textStatus,errorThrown, exception){
    alert('error');
    if (jqXHR.status === 0) {
        alert('Not connect.\n Verify Network.');
    } else if (jqXHR.status == 404) {
        alert('Requested page not found. [404]');
    } else if (jqXHR.status == 500) {
        alert('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
        alert('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        alert('Time out error.');
    } else if (exception === 'abort') {
        alert('Ajax request aborted.');
    } else {
        alert('Uncaught Error.\n' + jqXHR.responseText);
    }
    //alert(errorThrown);
        //alert(textStatus);
    }
});

}

calc_price先前在if语句中计算,但成功函数中警报中显示的值为“0”。

PHP和Wordpress钩子如下所示:

add_action('wp_ajax_datasender', 'datasender_callback');
add_action('wp_ajax_nopriv_datasender', 'datasender_callback');

function datasender_callback() {


       alert("PHP function successful");

}

关于如何解决这个问题的任何想法都会很棒。在此先感谢凯特。

2 个答案:

答案 0 :(得分:0)

alert是JavaScript,请尝试使用echo,如

echo json_encode($_POST['result']);

动作也需要成为数据参数的一部分

    data:({result: calc_price, action: 'data_sender'}),

答案 1 :(得分:0)

如果你收到0作为Wordpress的回复,大多数时候它意味着"错误",null或类似的东西。

尝试

add_action('wp_ajax_datasender', 'datasender_callback');
add_action('wp_ajax_nopriv_datasender', 'datasender_callback');

function datasender_callback() {

    wp_send_json( "PHP function successful" );

    wp_die();

}

但我认为你应该仔细阅读这样的教程:

https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

在Wordpress中有一些使AJAX调用更容易的事情,并帮助您正确地完成它。 (例如,对脚本进行排队和本地化。)