【问题标题】:Why can I use PHP in some of my Javascript but not in specific places?为什么我可以在我的一些 Javascript 中使用 PHP,但不能在特定地方使用?
【发布时间】:2017-12-11 06:30:27
【问题描述】:

我从根本上对代码中的某些内容感到困惑。

如果我在我的 .php 页面之一上编写代码:

$userEmail = $_SESSION["inputEmail"];

然后在我的一个 Javascript 函数中的 AJAX 调用中使用它:

function firstFunction() {
    $.ajax({
        url: someUrl.php?inputEmail='<?php echo $userEmail ?'>
        sync: true,
        success: function(result) {
          $("#someDiv").html(result)
         }
      })
}

我最终得到了我需要的结果。然而,我很困惑,因为如果在这个函数中,我做了这样的事情:

function secondFunction() {
    if (<?php echo $userEmail ?> == "test@test.com") {
        //do some stuff
    }
}

它不起作用。我已经阅读了上面这个确切场景的答案,但我不明白为什么我在这个例子中提供的第一行代码有效,而第二行却没有。

最初,我希望Javascript能够在上面的函数中读取$userEmail,但在查看页面源后,我发现它是评估什么的。它看起来像:

if(  == "test@test.com)

就像我说的,我已经查过了这部分。但现在我更加困惑了。为什么我可以在firstFunction() 下进行AJAX 调用,但在secondFunction() 下不行

【问题讨论】:

  • 该函数是否在单独的文件中?
  • 简单引号问题对吗? if ("&lt;?php echo $userEmail ?&gt;" == "test@test.com") {
  • 我的观点和@LawrenceCherone 一样,因为echo $userEmail 是一个字符串输出,必须用"test@test.com" 等引号括起来
  • 在庞大的现有电子邮件地址中检查 1 似乎是一种奇怪的方法:/
  • 或者 PHP 变量未在您尝试打印的位置定义。不过,Lawrence 是对的,生成的字符串需要在 javascript 中引用。

标签: javascript php jquery ajax server


【解决方案1】:

您的 ajax 正确运行的原因是因为您的 php 代码
在 qoute '&lt;?php echo $userEmail; ?&gt;' 内。

试试这个

function secondFunction() {
    var inputEmail = '<?php echo $userEmail; ?>';
    if (inputEmail == "test@test.com") {
        alert(inputEmail);
    }else{
        alert(inputEmail);
    }
}


就像Francis Avila 在您提供的链接中所说的(Using PHP in javascript's IF Statement)

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

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 2020-10-07
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多