2013-08-28 74 views
1

我知道這個問題已經被問了很多,所以我對任何冗餘道歉。然而,似乎根本無法使這種迴歸不是0以下以外的值是是,我已經在二十十二的主題內的functions.php底部代碼:阿賈克斯與WordPress的functions.php總是返回0

add_filter('views_edit-destination', 'so_13813805_add_button_to_views'); 
function so_13813805_add_button_to_views($views) 
{ 
    $views['my-button'] = '<button id="update-dest-cache" type="button" class="button"    title="Update Destinations Cache" style="margin:5px" onclick="updateDestCache()">Update Destinations Cache</button>'; 
    $views['my-button'] .= ' 
     <script type="text/javascript" > 
     function updateDestCache() { 
      jQuery.ajax({ 
       type: "POST", 
       url: ajaxurl, 
       dataType: "json", 
       action: "testAjaxFunction", 
       success: function(response){ 
        alert("Got this from the server: " + response); 
       }, 
       error: function(MLHttpRequest, textStatus, errorThrown){ 
        alert("There was an error: " + errorThrown); 
       }, 
       timeout: 60000 
      });  
     }; 
     </script> 
    '; 
    return $views; 
} 
function testAjax(){ 
    echo "ANYTHING!!!!"; 
    die(); 
} 
add_action('wp_ajax_testAjaxFunction', 'testAjax'); 
add_action('wp_ajax_nopriv_testAjaxFunction', 'testAjax'); 

該代碼添加一個按鈕添加到自定義帖子類型的編輯列表中,然後在單擊時運行該功能。按鈕顯示,函數運行,調用ajax函數,但0始終是響應。

爲什麼這繼續出現有什麼想法?

+0

請注意,從ajax調用中除去'url'變量和'dataType'變量會產生相同的結果。此外,導航到'/wp-admin/admin-ajax.php?action = testAjax'也會返回0 –

回答

2

我寫了我的javascript寫錯了。

function updateDestCache() { 
    jQuery.ajax({ 
     type: "POST", 
     url: ajaxurl, 
     data: { action: "testAjaxFunction" }, <---- THIS LINE WAS CHANGED 
     success: function(response){ 
     alert("Got this from the server: " + response); 
     }, 
     error: function(MLHttpRequest, textStatus, errorThrown){ 
     alert("There was an error: " + errorThrown); 
     }, 
     timeout: 60000 
    });  
}; 
0

ajaxurl僅在儀表板定義。如果你在前端使用它,你應該聲明它:

$admin_url = admin_url('admin-ajax.php'); 
$views['my-button'] .= ' 
     <script type="text/javascript" > 
     function updateDestCache() { 
      jQuery.ajax({ 
       type: "POST", 
       url: '. $admin_url .', 
       dataType: "json", 
       action: "testAjaxFunction", 
       success: function(response){ 
        alert("Got this from the server: " + response); 
       }, 
       error: function(MLHttpRequest, textStatus, errorThrown){ 
        alert("There was an error: " + errorThrown); 
       }, 
       timeout: 60000 
      });  
     }; 
     </script> 
    '; 
+0

這實際上是WordPress CMS中的僅管理功能。因此,阿賈克斯似乎總是被定義的。我也認爲,這意味着'ADD_ACTION(「wp_ajax_nopriv_testAjaxFunction」,「testAjax」);'是不必要的代碼,可以刪除,但因爲它不工作,我想我會離開它... –