2011-10-10 100 views
0

我试图在WordPress插件中使用随机数。我有一个我想要使用nonce的表单。在Wordpress插件中使用Nonce与Ajax

在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'); 

在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); 
        }); 

我是正确张贴在现时jQuery的?

在PHP中:

function the_action_function() { 
    if(! wp_verfiy_nonce($nonce, 'myajax-nonce')) die ('Busted!'); 
//function continues 

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

谢谢。

回答

4

有两件事是错误的。

通过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); 
      }); 

这将发送参数my_nonce中的现时值。现在,服务器端可以更换

if(! wp_verify_nonce($nonce, 'myajax-nonce')) die ('Busted!'); 

if(! wp_verify_nonce($_POST['my_nonce'],'myajax-nonce')) die ('Busted!'); 

一起来看看jQuery.post文档和wp_verfiy_nonce将帮助您更好:)

+0

嗨sbrajesh,非常感谢您的帮助。我对您建议的代码进行了更改。我也删除了'ajaxurl'中的下划线。不幸的是,我收到“致命错误:调用未定义函数wp_verfiy_nonce()”。听起来就像由于某种原因没有及时加载功能。有任何想法吗?谢谢 ! – Laxmidi

+0

我在wp_verify_nonce中也有拼写错误。打字不好。谢谢! – Laxmidi

+0

你确定它正在工作。如果它不 变化 '$数据=阵列( 'ajax_url'=> ADMIN_URL( '管理员-ajax.php'), 'my_nonce'=> wp_create_nonce( 'myajax-随机数') );' 到 '$数据=阵列( 'ajaxurl'=> ADMIN_URL( '管理员-ajax.php'), 'my_nonce'=> wp_create_nonce( 'myajax-随机数') ); ' 或者在我的代码中用'ajax_url'替换'ajaxurl',就像你在数据中一样 – sbrajesh