問題描述

我特別是 jQuery 和 AJAX 比較新。我有一個小問題,返回值總是為 0,雖然我認為這實際上是成功的消息,它沒有返回任何東西。

我已經瀏覽了 Google 的節目,我在 PHP 回調中使用了 die() 函數,我相信 add_actions 是正確的。

我在一個本地的主機工作,雖然我懷疑這影響到它,這一切都在管理,而不是前端。我還檢查了 js 是入隊和本地化的。

我在 chrome 開發者區域收到 200 OK 消息。

我還測試了 http://codex.wordpress.org/AJAX_in_Plugins 的基本 AJAX,並且還返回 0,這使我想知道它是否與下面的代碼不同。

現在我只是想把它發回給 jQuery 。任何幫助將不勝感激。

jQuery

jQuery(document).ready(function(){
    jQuery('.cl_link_buttons').val('id').click(function() {

            var currentid = jQuery(this).attr('id');

            //alert(currentid);
            console.log(currentid);

            jQuery.ajax ( data = {
                action: 'cleanlinks_ajax_get_post_data',
                url: ajaxurl,
                type: 'POST',
                dataType: 'text',
                "currentid" : currentid

            });

            jQuery.post(ajaxurl, data, function(response) {

                var dataz = response;
                alert( dataz );
                console.log (dataz); //show json in console


            });

            return false;

    }); //end click event
}); //end doc ready

PHP

add_action("wp_ajax_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
add_action("wp_ajax_nopriv_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");

function cleanlinks_ajax_get_post_data() {

$from_ajax =  $_POST['currentid'];

echo "do" . $from_ajax . "something";

die();


}

最佳解決方案

0 響應意味着該操作未設置 (在 ajax 數據中) 或該動作的回調函數無法找到。

次佳解決方案

您需要做的是在函數的末尾添加 die();

看到原因和更多在這裏:http://codex.wordpress.org/AJAX_in_Plugins

筆記:

  • 在執行 die 之前,應該使用 echo 。這將防止服務器錯誤,並在調試時有所幫助。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。