2011-10-10 103 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