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

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

问题描述

我正在尝试制作一个确认框,它将需要执行哪些PHP代码。
继承我的代码:

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>

问题是,即使我点击YES,$ confirmation和from函数返回1确认和布尔值。
无论我点击什么,(取消或确定),其中一个应该是0(我之前已经宣布$确认)
但是使用if和else块的两个代码!
通常它就像这样工作

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

推荐答案

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

You fundamentally misunderstand what PHP is doing.

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

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>

您需要在浏览器中运行javascript中要执行的操作,或者需要向服务器发送新请求并使用您的回复(直接或间接)获取新页面。

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天全站免登陆