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 に答える