1

我知道这个问题被问了很多,所以我为任何冗余道歉。但是,似乎无法让它返回 0 以外的值。下面是我在 Twenty-Twelve 主题中的 functions.php 底部包含的代码:

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。

关于为什么这种情况继续发生的任何想法?

4

2 回答 2

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
   });    
};
于 2013-09-06T20:20:38.607 回答
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>
    ';
于 2013-08-29T05:12:15.560 回答