AJAX没有出现在Firebug控制台中

时间:2012-06-04 17:56:45

标签: jquery ajax

免责声明:不确定这是否与WordPress有关。

我正在关注simple tutorial以检查AJAX是否在我的WordPress本地主机中运行。

我的ajax-test.js:

jQuery(document).ready( function($){
    $(".ajax-link").click( function(){
        var data = {
            action: 'test_response',
            post_var: 'this will be echoed back'
        };
        $.post(the_ajax_script.ajaxurl, data, function(response) {
                                                       alert(response);
                                                       });
        return false;
    });
});

在我的插件中,我将脚本添加到wp_print_scripts()并添加处理函数:

function test_ajax_load_scripts(){
    wp_enqueue_script("ajax-test", plugin_dir_url( __FILE__ ) . 'ajax-test.js', array( 'jquery' ) );
    wp_localize_script('ajax-test', 'the_ajax_script', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );
}
add_action('wp_print_scripts', 'test_ajax_load_scripts');

function text_ajax_process_request(){ 
    if(isset($_POST["post_var"])){
        $response = $_POST["post_var"];
        echo $response;
        die();
    }
}
add_action('wp_ajax_test_response', 'test_ajax_process_request');

我使用href =“#”获得链接输出,然后单击它,它将我带到页面顶部。我检查Firebug,我可以确认ajax-test.js已加载到标题中。控制台里什么都没有。

我还能如何调试警报未发生的原因?

2 个答案:

答案 0 :(得分:0)

如果您返回false并且页面仍然跳到顶部,则会出现javascript错误。 $.post失败的可能性很大。尝试向$.post添加错误回调以获取更多信息。

$.post(...).fail(function(){
    console.log(arguments)
});

另一种可能性是甚至没有达到点击处理程序。在这种情况下,请确保选择器正确,并且在运行代码时页面上存在元素。如果元素是通过ajax或javascript添加的,那么您需要在添加该元素之后运行此代码,或者您需要使用.on.delegate的事件委派附加事件

$(document).on("click",".ajax-link",function(){...});

答案 1 :(得分:0)

您的活动广告功能需要e.preventDefault()

$(".ajax-link").click( function(e){ //<--------- e
    e.preventDefault(); //<-------- preventDefault()   
    var data = {
        action: 'test_response',
        post_var: 'this will be echoed back'
    };
    $.post(the_ajax_script.ajaxurl, data, function(response) {
        alert(response);
    });        
});