gpt4 book ai didi

javascript - 如何根据Jquery中设置的cookie验证div

转载 作者:行者123 更新时间:2023-12-02 16:59:37 25 4
gpt4 key购买 nike

我根据屏幕宽度在Jquery中设置cookie。像这样

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){

var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
});
</script>

然后我使用这些 cookie 来验证 php 中的 div 以及同一文件中的其他一些参数,如下所示

<?php
if($current_item == 2 && $_COOKIE['adds'] == '1')
{
//place the adsense after the third ad.
?>
<div id="bloque" class="addsTpl addBigphone" style="min-height:90px">
<div class="google_add">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- resultmobile -->
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:90px"
data-ad-client="ca-pub-765756"
data-ad-slot="657567"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
</div
<?php
}
?>

到目前为止一切顺利。我面临的问题是 if() 语句只有在我重新加载页面后才变为 true。

我的理解是,cookie是在第一次执行服务器if()语句后设置的,因为Jquery只有在服务器脚本加载完成后才会执行。

任何人都可以建议我任何其他可以用来执行此操作的方法吗?

感谢和问候

最佳答案

这是正确的,服务器端代码首先运行并为您提供页面,然后才执行 JavaScript - 这对您来说太晚了

您可以将运行以设置 cookie 的窗口大小测试移动到应用程序中的较早页面(例如登录页面),或者您可以有一个“隐藏”页面,该页面运行您的 javascript,然后立即重定向到您的主页面页面例如

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){

var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
// redirect to the actual page you want
document.location.href = 'new main page url'
});
</script>

因此,您的隐藏页面永远不会呈现 - 它只是运行 JavaScript,然后重定向到主页。

希望有帮助 加勒特

关于javascript - 如何根据Jquery中设置的cookie验证div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com