在 javascript 的 IF 语句中使用 PHP [英] Using PHP in javascript's IF Statement

查看:28
本文介绍了在 javascript 的 IF 语句中使用 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个确认框,该框将希望执行哪些 php 代码.这是我的代码:

问题是,即使我点击是,$confirmation 和来自 defined() 函数的布尔值也返回 1.无论我点击什么,(取消或确定)其中一个应该是 0(我之前已经声明过 $confirmation)但是 if 和 else 块中的两个代码都使用了!通常它是这样工作的

解决方案

你从根本上误解了 PHP 在做什么.

在页面发送到您的浏览器之前,PHP 会在服务器上进行评估.当浏览器看到它并执行 javascript 时,所有的 PHP 都消失了.

在包含此代码的浏览器窗口中使用浏览器的查看源代码".你会看到它看起来像这样:

您要么需要在 javascript 中实现您想要在浏览器上运行的操作,要么需要向服务器发送新请求并通过您的响应(直接或间接)返回一个新页面.

I am trying to make a confirm box which will desire which php code will be executed. Heres my code:

<script type="text/javascript">
    var answer = confirm('Are you sure?');

    if(answer==true)
       {
          <?php $confirmation = 1; ?>
       } 
    else 
       { 
          <?php define("CONFIRMATION", 1, true); ?>
       }
         alert('<?php echo $confirmation; ?>')
         alert('<?php echo defined("CONFIRMATION"); ?>')
</script>

The problem is , even if i click YES, $confirmation and boolean from defined() function returns 1. Whatever I click, (cancel or ok) one of them should be 0 (I've already declared $confirmation before) But both of codes at if and else blocks are used! Normally it works like this

解决方案

You fundamentally misunderstand what PHP is doing.

PHP is evaluated on the server before the page is sent to your browser. By the time the browser sees it and executes the javascript, all the PHP is gone.

Use your browser's "view source" on the browser window with this code in it. You'll see it looks like this:

<script type="text/javascript">
var answer = confirm('Are you sure?');

if(answer==true)
   {
             } 
else 
   { 
             }
     alert('1')
     alert('1')
</script>

You either need to implement what you want to do in javascript to run on the browser, or you need to send a new request to the server and get a new page back (either directly or indirectly) with your response.

这篇关于在 javascript 的 IF 语句中使用 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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