2012-03-14 67 views
0

希望有人能幫助我。阿賈克斯不是在WordPress的工作

我已經使用了下面的教程爲指導,以在WordPress http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

運行Ajax我在functions.php文件

wp_enqueue_script('my-ajax-request','/wp-content/themes/son-of-suffusion/js/ajax.js', array('jquery')); 
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) 
wp_localize_script('my-ajax-request', 'MyAjax', array('ajaxurl' => admin_url('admin-ajax.php'))); 


/*AJAX STUFF*/ 

// this hook is fired if the current viewer is not logged in 
do_action('wp_ajax_nopriv_' . $_REQUEST['action']); 
// if logged in: 
do_action('wp_ajax_' . $_POST['action']); 


// if both logged in and not logged in users can send this AJAX request, 
// add both of these actions, otherwise add only the appropriate one 
add_action('wp_ajax_nopriv_myajax-submit', 'myajax_submit'); 
add_action('wp_ajax_myajax-submit', 'myajax_submit'); 

function myajax_submit() { 

    echo 'ajax submitted';  

    die; 

    // IMPORTANT: don't forget to "exit" 
    exit; 

} 

以下代碼,該代碼在我ajax.js文件

// JavaScript Document 

jQuery(function($){ 
    $(".selected").click(function() { 

     alert("jQuery is working"); 
     $.post(MyAjax.ajaxurl, { 
    action: 'myajax-submit', 
     postID : MyAjax.postID 

    }, function(response) { 

    $("#content").html("loading..."); 
    $("#content").html(response);  


    }); 

    }); 


}) 

jQuery的警報顯示,但Ajax代碼不工作和全頁面刷新。難道我做錯了什麼?當我使用Firebug時,我的js代碼中沒有錯誤。

預先感謝您

回答

2

在你點擊功能,傳似below.And添加事件

ev.preventDefault

$(".selected").click(function (ev) { 

    //prevents default action of the element 
    ev.preventDefault(); 
    alert("jQuery is working"); 
    $.post(MyAjax.ajaxurl, { 
    action: 'myajax-submit', 
    postID : MyAjax.postID 

    }, function(response) { 

$("#content").html("loading..."); 
$("#content").html(response);  


}); 

}); 
+0

嗨DG3謝謝您的回答。我加入的代碼,你建議的線路和我第一次點擊了該鏈接,我看到了Ajax代碼顯示短暫,但還是完整的頁面加載,當我再次進行同樣的動作,我沒有看到Ajax代碼顯示。我懷疑Ajax代碼運行,但是當頁面內容顯示在內容DIV – Amara 2012-03-14 21:38:57

+0

我的壞對不起,這完美地工作,我錯過了增加EV的功能被覆蓋。你搖滾,謝謝:)在這一兩天,準備把我的筆記本電腦從窗戶裏拿出來。謝謝 :) – Amara 2012-03-14 21:47:31