本文介绍了简单的jquery.ajax返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这些无处不在,但是我似乎看不到代码中的错误.我正在使用数据类型json进行简单的ajax调用.此调用似乎成功,但未返回任何内容,并且警报显示undefined.

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:

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

请注意,这是通过Wordpress完成的,因此是init函数.以为我会妥善保管.

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

推荐答案

问题是POST没有与ajax调用一起传递"action".在网址中添加操作"后,一切正常.

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.

这篇关于简单的jquery.ajax返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:10