問題描述

我想知道處理 AJAX 呼叫的首選方法是什麼。應該使用相同的外掛 php 檔案來處理 POST 還是單獨一個?哪個更乾淨或更安全?

最佳解決方案

「更安全,更乾淨」 的方式是使用 wordpress 和 wp_ajax 鉤子中的 admin-ajax.php 從您的外掛檔案中呼叫處理函式,並使用 wp-nonce 來檢查呼叫的完整性。

例如:

你的 ajax JQuery 呼叫將是

<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        action: 'ACTION_NAME',
            Whatever: '1234',
            _ajax_nonce: '<?php echo wp_create_nonce( 'my_ajax_nonce' ); ?>'

    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    // If you need it on a public facing page, uncomment the following line:
    // var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>

在你的外掛檔案中新增

//if you want only logged in users to access this function use this hook
add_action('wp_ajax_ACTION_NAME', 'my_AJAX_processing_function');

//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_ACTION_NAME', 'my_AJAX_processing_function');

*如果你想登入的使用者和訪客透過 ajax 訪問你的函式,新增兩個鉤子。 * ACTION_NAME 必須與您的 ajax POST 中的動作值相匹配。

那麼在你的函式中只要確保請求來自有效的來源

function my_AJAX_processing_function(){
   check_ajax_referer('my_ajax_nonce');
   //do stuff here
}

希望這可以幫助

參考文獻

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