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

I've been trying to use AJAX to send across a variable from a JS file and trigger a PHP file in Wordpress. The function connects to the PHP file however the variable it sends across stores the value "0" . I've tried many solutions, but I can't quite nail down this problem. The JS code is below:

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.
 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.
' + jqXHR.responseText);
    }
    //alert(errorThrown);
        //alert(textStatus);
    }
});

}

The value calc_price is calculated prior in an if statement, but the value shown in the alert in the success function is "0".

The PHP and Wordpress hooks are show below:

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

function datasender_callback() {


       alert("PHP function successful");

}

Any ideas on how to solve this problem would be great. Thanks in advance, Kate.

alert is JavaScript, try using echo, as in

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

also action needs to be part of your data parameter

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

If you receive 0 as a response with Wordpress, most of the time it means "error", null or something like that.

Try

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();

}

But I think you should go over a tutorial like this:

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

In Wordpress there are a couple of things that make the AJAX call easier, and helps you do it correctly. (E.g. enqueuing and localizing the script.)