Я хотел бы передать переменную на определенную страницу. Я нашел простой пример, объясняющий, как использовать ajax с wordpress.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