duanmiaosi0150 2011-10-18 20:18
浏览 46
已采纳

Javascript和PHP执行if / else语句

I'm trying a simple if/else statement with Javascript & PHP (with jQuery cookie plugin).

My problem: every time this script fires, it executes both IF and ELSE statements. Even when my cookie is set, it creates a new one and adds it into my database. Am I using both languages properly?

Here's what it looks like:

<script type="text/javascript"> 

//check to see if cookie is present
if ($.cookie('uid')) {
    var userCookie = $.cookie('uid');
    alert(userCookie);      

}
else {
    //create cookie and check to see if it is taken
    <?php 
    $success = false;
    while (!$success) {
        $cookie = createUniqueCookie();
        $success = checkIfCookieIsTaken($cookie);
    }       

    //store into database and set into browser
    if ($result = $mysqli->query("INSERT INTO users (cookie) VALUES ('" . $cookie . "')")) {
    ?>
                $.cookie('uid', '<?php echo $cookie ?>', { expires: 730, path: '/' });
                var userCookie = $.cookie('uid');
                alert('new cookie for user is '+ userCookie);
    <?php
    }
    ?>
}
  • 写回答

2条回答 默认 最新

  • duangan4070 2011-10-18 20:21
    关注

    It looks like you are trying to run php and javascript at the same time. That doesn't work like that.

    All the PHP is being run on the server. Every bit of it is parsed, and the resulting code is send to the browser. If there is any javascript in there that gets run by the browser, but then the 'evil' is allready done.

    You can't just mix client and server code like that :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)