PHP& jQuery传递变量 [英] PHP & JQuery passing variables

查看:93
本文介绍了PHP& jQuery传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为WordPress创建一个插件,并且被困了两天,试图找到一种将变量及其值从jQuery传递到PHP的方法,此刻,我不得不设置条件内部的布尔输出cookie,然后使用PHP读取它以执行和更新.

I am creating a plugin for WordPress and I have been stuck for a two days trying to figure a way of passing variables and it's values from jQuery to PHP, at the moment I have resorted to setting the boolean output of a conditional inside a cookie and then reading it with PHP in order to perform and update.

jQuery 我正在使用activeStatus在jQuery中执行一些条件,然后设置cookie以继续在PHP中执行其他条件集

jQuery I am using activeStatus to perform some conditionals in jQuery and then i am setting a cookie in order to continue performing other set of conditionals in PHP

var activeStatus = true;
jQuery.cookie('activeStatus', true, {expires: 1, path: '/'});

PHP 现在,我们读取jQuery设置的cookie并执行更新

PHP now we read the cookie set by jQuery and perform update

if (!isset($_COOKIE["uniqueUser"])) { //unique visitor
            if ($_COOKIE["activeStatus"] == 'true') { //if cookie found and true
                $uniqueVisitor = get_option('stats');
                $uniqueVisitor['uniqueVisits']+=1;
                update_option('stats', $uniqueVisitor);
             }

现在的问题是,因为只有在第二次刷新时才能读取cookie,所以将永远不会执行第二个有条件的操作,因此,更新将永远不会发生,因为cookie已经设置好了.因此,我希望实时传递变量.

The problem now is that the second if conditional will never be performed since cookies can only be read on the second refresh, hence, the update will never take place because the cookie would have been set. for this reason I wish to pass the variable in real time.

我想提到的另一件事是,我正在使用PHP打印整个javascript,即

One more thing I would like to mention is that I am using PHP to print the whole javascript i.e

<?php

add_action('exec_script', 'script');
function script() {
?>

<script type="text/javascript">
//code
</script>

<?php
}

为适应我的目的,我需要在页面中打印js代码,并且无法将其保存在js文件中.

To fit my purposes I need to print the js code in the page and cannot save it in a js file.

有人有什么主意吗?

推荐答案

您应该使用名为ajax的PHP脚本设置co​​okie.然后,当您加载下一页时,已经为PHP脚本设置了该页面以找到它.我承认我不知道jquery.cookie的来龙去脉,所以这可能不是答案.但这就是我的开始.

You should set the cookie with a PHP script called with ajax. Then when you load the next page, it will already be set for the PHP script to find it. I admit I don't know the ins and outs of jquery.cookie so this may not be the answer. But this is what I'd start with.

这篇关于PHP&amp; jQuery传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆