简体   繁体   English

在 external.js 文件中调用 php 变量

[英]calling php variable in external.js file

I am trying to access a PHP variable from an external file.js, then use the variable to control output of a function in the file.js .我试图从外部 file.js 访问 PHP 变量,然后使用该变量来控制file.js函数的输出。

i tried using input hidden field to hold the variable , and in the file.js , use $("#id").val() to retrieve the text value of the input, but it still does not work.我尝试使用输入隐藏字段来保存变量,并在file.js中使用$("#id").val()来检索输入的文本值,但它仍然不起作用。

myfile.php i have this myfile.php 我有这个

<html>
<head>
    <script type="javascript" src="file.js"></script>
</head>
<body>
    <input type="hidden" id="myPhpValue" value="<?php echo $phpValue ?>">

and in file.js i have thisfile.js我有这个

$(script);

function script(){
    //some codes 
    displayUser();
}

function displayUser(){ 
    var user = $("#myPhpValue").val();
    alert ("the user is "+user);
}

If user is Mike, i expect the output to show "the user is mike", but nothing shows如果用户是 Mike,我希望输出显示“用户是 Mike”,但没有显示

The possible reason that your code isn't working are:您的代码不起作用的可能原因是:

  1. You haven't embedded jQuery library and been using $() identifier您还没有嵌入 jQuery 库并且一直在使用$()标识符
  2. Your PHP variable $phpValue is empty您的 PHP 变量$phpValue为空

The following code works:以下代码有效:

 var user = $("#myPhpValue").val(); alert ("the user is "+user);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <input type="hidden" id="myPhpValue" value="mike">

In your html move the script tag where your body's tag is closed.在你的 html 中移动你的 body 标签关闭的脚本标签。 if it didn't work again then change your js code and write on this way如果它再次不起作用,则更改您的 js 代码并以这种方式编写

var element = document.querySelector("#myPhpValue").value; alert(element);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM