2012-06-04 52 views
0

免責聲明:不知道這是WordPress的相關與否。AJAX沒有出現在螢火蟲控制檯

我正在關注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已加載到標題中。控制檯中沒有任何東西。

我該怎麼調試爲什麼警報沒有發生?

回答

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); 
    });   
}); 
+1

你應該能夠擺脫「返回false」;還有preventDefault。 – adamzwakk

+0

@adamzwakk是的,這是正確的 – Jason

0

如果您返回false並且頁面仍然跳轉到頂部,您將收到JavaScript錯誤。很可能$.post失敗。嘗試將錯誤回調添加到$.post以獲取更多信息。

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

另一種可能性是甚至沒有達到點擊處理程序。在這種情況下,請確保選擇器正確,並且代碼運行時頁面上存在該元素。如果該元素是通過AJAX或JavaScript添加,你需要這個代碼運行之後的元素被加入,或者你需要使用事件代表團事件與.on.delegate

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