我想將變量傳遞給特定頁面。我找到了一個簡單的例子來解釋如何在wordpress中使用ajax。Wordpress將ajax值傳遞給使用Wordpress的特定頁面
的JavaScript:
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
PHP的那條在functions.php
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if (isset($_REQUEST)) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ($fruit == 'Banana') {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action('wp_ajax_example_ajax_request', 'example_ajax_request');
wp_localize_script('ajax-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
插入可惜我不能傳遞變量。我檢查了代碼,我得到這個錯誤:
Error: ajax_object is not defined
你也許知道另一種獲得相同結果的方法嗎?
** ** wp_localize_script會希望有一個名爲** ajax_object變量**,所以你可以嘗試評論這個,看看它是否有效,所以你會知道錯誤是從那裏來的? – TheFallen
嗨,LoicTheAtzec 我不太明白你的例子。 我可以請你用blockquote寫你的建議嗎? – Daniel