問題描述
我想知道處理 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。