simple jquery.ajax returns undefined

2019-08-22 02:38发布

问题:

I know these are everywhere but I can't seem to see the error in my code. I'm making a simple ajax call with datatype json. This call seems to succeed but does not return anything and the alert prints undefined.

javascript:

jQuery(document).ready(function() {
    if(jQuery('#statesel').length) {
        var dataString;

        dataString = "nonce=" + dynoselect.post_dyno_select_nonce;
        jQuery.ajax({
            type: "POST",
            url: dynoselect.ajaxurl,
            dataType: "json",
            data: dataString,
            success: function(result) {
                alert(result.status);
            }
        });
    }
}

php:

<?php
add_action("init", "ci_enqueuer");
add_action("wp_ajax_dyno_select", "dyno_select");
add_action("wp_ajax_nopriv_dyno_select", "dyno_select");

function ci_enqueuer() {
    wp_register_script('dyno_select_script', plugins_url('/js/dyno_select_script.js', __FILE__), array('jquery'));
    wp_localize_script('dyno_select_script', 'dynoselect', array('ajaxurl' => admin_url('admin-ajax.php'), 'post_dyno_select_nonce' => wp_create_nonce('dyno_select_nonce')));
    wp_enqueue_script('jquery');
    wp_enqueue_script('dyno_select_script');
}

function dyno_select() {
    $nonce = $_POST['nonce'];

    //checking token, looking for funny business
    if (!wp_verify_nonce( $nonce, 'dyno_select_nonce')) {
        $result['status'] = 'nonce failed';
        $result = json_encode($result);
        echo $result;
        die();
    }

    $result['status'] = 'success';
    echo json_encode($result);
    die();
}
?>

Just as a note this is being done with Wordpress, hence the init function. Thought I would keep that in for good measure.

回答1:

jQuery.ajax has 3 arguments for success callback. First one is a data with your specified type (JSON in your example). So it has no status property.

In addition, when you get alert on success, It means that Content-type has been set correctly and is a valid JSON object.

Try using :

success: function(result, status, XHR) {
     alert(XHR.status);
}


回答2:

That JSON parameter string doesn't look like it will work. Is the call posting to the server correctly?

If it is, ignore this.

If not, I suggest including json2.js (http://www.json.org/js.html) and stringify-ing your data parameter before calling jQuery.ajax:

var jsonData = { param1: 'something', param2: 999 };
var dataString = JSON.stringify(jsonData);

EDIT: the example in this accepted SO answer doesn't stringify, but it does construct and pass a valid JSON object. And shows the server side parsing.



回答3:

The problem was that the POST did not pass "action" along with the ajax call. As soon as "action" was added to the url, everything worked.