在WordPress插件中使用Nonce和Ajax

Lax*_*idi 1 wordpress jquery nonce

我正在尝试在WordPress插件中使用nonce.我有一个表格,我想用nonce.

在PHP中:

function csf_enqueue() {

//I have other scripts enqueued in htis function 
wp_enqueue_script('my-ajax-handle', plugin_dir_url(__FILE__).'file-path', array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'google-maps'));

$data = array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'my_nonce' => wp_create_nonce('myajax-nonce')
);

wp_localize_script('my-ajax-handle', 'the_ajax_script', $data );

}

add_action('wp_enqueue_scripts', 'csf_enqueue');
add_action('wp_ajax_the_ajax_hook', 'the_action_function');
add_action('wp_ajax_nopriv_the_ajax_hook', 'the_action_function');
Run Code Online (Sandbox Code Playgroud)

在jQuery文件中:

jQuery.post(the_ajax_script.ajaxurl, {my_nonce : the_ajax_script.my_nonce}, jQuery("#theForm").serialize() + "&maxLat="+ csf_dcscore_crime_map_bounds[0] + "&maxLong="+ csf_dcscore_crime_map_bounds[1] + "&minLat="+ csf_dcscore_crime_map_bounds[2] + "&minLong="+ csf_dcscore_crime_map_bounds[3],
                    function(response_from_the_action_function){
                        jQuery("#response_area").html(response_from_the_action_function);
                    });
Run Code Online (Sandbox Code Playgroud)

我是否在jQuery中正确发布了nonce?

在PHP中:

function the_action_function() {
   if( ! wp_verfiy_nonce( $nonce, 'myajax-nonce')) die ('Busted!');
//function continues
Run Code Online (Sandbox Code Playgroud)

有什么建议?如果我删除所有关于nonce的代码,一切正常.关于它为什么不起作用的任何想法?或者我该如何调试它?谢谢!

谢谢.

小智 5

有两件事是错的.

通过jQuery post方法发送数据,你不能像你一样发送一个对象+一个查询字符串.相反,您需要发送查询字符串格式或对象格式数据.为了方便您的使用,我将使用查询字符串格式.所以邮政编码应该是这样的

jQuery.post( the_ajax_script.ajaxurl, 
             jQuery("#theForm").serialize() + 
                    "&maxLat="+ csf_dcscore_crime_map_bounds[0] + 
                    "&maxLong="+ csf_dcscore_crime_map_bounds[1] + 
                    "&minLat="+ csf_dcscore_crime_map_bounds[2] + 
                    "&minLong="+ csf_dcscore_crime_map_bounds[3] +
                    "&my_nonce="+ the_ajax_script.my_nonce,
             function(response_from_the_action_function) {
                 jQuery("#response_area")
                     .html(response_from_the_action_function);
             });
Run Code Online (Sandbox Code Playgroud)

这将在参数my_nonce中发送nonce.现在服务器端可以替换

if( ! wp_verify_nonce( $nonce, 'myajax-nonce')) die ('Busted!');
Run Code Online (Sandbox Code Playgroud)

if( ! wp_verify_nonce( $_POST['my_nonce'],'myajax-nonce')) die ('Busted!');
Run Code Online (Sandbox Code Playgroud)

看一下jQuery.postwp_verfiy_nonce的文档会帮助你更好:)