admin管理员组文章数量:1418609
I'm wondering what the preferred method is for dealing with AJAX calls. Should one use the same plugin php file to process the POST or a separate one? Which is cleaner or safer?
I'm wondering what the preferred method is for dealing with AJAX calls. Should one use the same plugin php file to process the POST or a separate one? Which is cleaner or safer?
Share Improve this question asked Feb 13, 2011 at 1:32 JamesJames 6256 silver badges5 bronze badges1 Answer
Reset to default 47the "safer and cleaner" way would be to use admin-ajax.php that comes with wordpress and wp_ajax
hook to call your processing function from your plugin file and use wp-nonce to check the integrity of the call.
for example:
your ajax JQuery call would be
<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>
then in your plugin file add
//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');
*if you want logged in users and guests to access your function by ajax then add both hooks. *ACTION_NAME must match the action value in your ajax POST.
then in your function just make sure the request came from valid source
function my_AJAX_processing_function(){
check_ajax_referer('my_ajax_nonce');
//do stuff here...
}
Hope this Helps
本文标签: What39s the preferred method of writing AJAXenabled plugins
版权声明:本文标题:What's the preferred method of writing AJAX-enabled plugins? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745297502a2652167.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论