[英]Using variables defined in functions.php WORDPRESS
I have a variable that is being pulled from a jQuery into php in my functions.php file. 我在我的functions.php文件中有一个从jQuery拉入php的变量。
But I'm unable to use it in a page. 但是我无法在页面中使用它。
When I echo it from functions.php, it appears in the console in chrome, but has a 0 appended.. 当我从functions.php中回显它时,它以镶边形式出现在控制台中,但附加了0。
If I try to echo it in my template page, I get nothing. 如果我在模板页面中回显它,那么我什么也没得到。
Code below. 下面的代码。
jQuery jQuery的
var pie = 131;
$.ajax({
url: ajaxurl, //super global supplied by Wordpress; do not change
type: 'POST',
data: {
action: 'get_post_id', //this is correct
pie : pie
},
success: function (data){
console.log(data);
}
});
functions.php functions.php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_get_post_id', 'my_ajax_function' );
add_action( 'wp_ajax_get_post_id', 'my_ajax_function' );
function my_ajax_function() {
$new_pie = isset($_POST['pie']) ? $_POST['pie'] : false;
echo($new_pie);
}
template-page.php template-page.php
<?php echo($new_pie); ?>
Thanks in advance. 提前致谢。
I addressed this in a previous question of yours. 我在上一个问题中解决了这个问题。
The 0 is being appended to the Ajax call because you need to die()
after the echo. 0被附加到Ajax调用中,因为您需要在回显之后die()
。
echo $new_pie;
die();
This will stop the 0
from being appended. 这将阻止添加0
。
As for the return of the data from the AJAX call, you need to do something with it, like append it to an element. 至于从AJAX调用返回的数据,您需要对其进行处理,例如将其附加到元素上。
$('#elementID').append(data);
Which in this case, elementID
is the ID of an element such as a DIV or P. 在这种情况下, elementID
是元素(例如DIV或P)的ID。
sidenote 边注
There's no reason to use the following: 没有理由使用以下内容:
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
Wordpress has created the javascript ajaxurl
variable for you and has been doing so since WP 2.8. Wordpress为您创建了javascript ajaxurl
变量,并且自WP 2.8起就一直在这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.