简体   繁体   English

在JavaScript中嵌入PHP

[英]Embedding PHP within javascript

I'm trying to create a messaging system that opens when you click the "New Message" button. 我正在尝试创建一个消息系统,当您单击“新消息”按钮时会打开。 I'm using HTML, PHP, and javascript. 我正在使用HTML,PHP和javascript。

I have a button set up with a container to append a textarea into. 我有一个设置有容器的按钮,用于将文本区域附加到其中。 I am doing this with javascript DOM. 我正在使用javascript DOM执行此操作。 This part I have no problem with, it is trying to get PHP inside javascript. 这部分我没有问题,它试图在javascript中获取PHP。

So let's say I have a variable: 假设我有一个变量:

<?php $my_name = "Eric" ?>

Would I be able to call this in javascript? 我可以用javascript调用它吗? If not, are there any any other ways to approach this? 如果没有,还有其他方法可以解决吗?

Here is my full code: 这是我的完整代码:

HTML: HTML:

<html>
<head>
    <link type="text/css" rel="stylesheet" href="message.css"/>
    <script type="text/javascript" src="js/message.js"></script>
</head>

<body>
    <div id="container"></div>

    <button id="new_message" onclick="createMessage()">New Message</button> 
</body>
</html>

CSS: CSS:

#container {
    position: absolute;
    height: 443px;
    width: 743px;
    border: 1px solid black;
    border-radius: 0 0 20px 0;
    margin-top: 100px;
}

Javascript: 使用Javascript:

function createMessage() {
    var form = document.createElement("form");
    form.name = "form_input";
    form.method = "POST";
    form.action = "messages.php";
    container.appendChild(form);

    var textarea = document.createElement("textarea");
    textarea.name = "message_input";
    textarea.cols = 84; 
    textarea.rows = 16; 
    textarea.id = "message_input"; 
    container.appendChild(textarea);
};

I'm trying to do something similar to Facebook, that when you click on the messages button, a pop up box appears with php inside of it. 我正在尝试做类似于Facebook的事情,当您单击消息按钮时,会出现一个弹出框,其中带有php。

Can this be done the way I'm doing it with javascript or do I have to use something else? 可以通过使用javascript的方式来完成此操作,还是必须使用其他方法?

Thanks for your help! 谢谢你的帮助!

The best way to think of this is to go back to the order of execution for the different scripting languages used in the page. 考虑这一点的最佳方法是返回页面中使用的不同脚本语言的执行顺序。 That order of execution is something like this: 执行顺序是这样的:

(1) PHP is run on your server. (1)PHP在您的服务器上运行。 It spits out a bunch of HTML and/or Javascript and/or CSS which is sent as a response to the user's browser. 它吐出了一大堆HTML和/或Javascript和/或CSS,作为对用户浏览器的响应而发送。

(2) The user's browser receives a response, renders the HTML, and executes the Javascript. (2)用户的浏览器接收响应,呈现HTML,并执行Javascript。

In practical terms, this means you can make your Javascript dependent on your PHP , but not the other way around. 实际上,这意味着您可以使Javascript依赖于PHP ,而不能相反。

From your question, it looks like it would be OK for you to always execute the PHP and simply display the result when a user clicks on a button. 从您的问题看来,始终执行PHP并在用户单击按钮时仅显示结果就可以了。 So have your PHP spit out some Javascript like so: 因此,让您的PHP吐出一些Javascript,如下所示:

<script type="text/javascript">
    var myName = '<?php echo addslashes($my_name)?>';
</script>

[Note: you may want to do additional, or different, sanitization.] [注意:您可能需要进行其他或不同的消毒。]

would make sense to pass the variable to the javascript via the button. 通过按钮将变量传递给javascript会很有意义。 eg. 例如。

<button id="new_message" onclick="createMessage('<?php echo $my_name;?>')">New Message</button>

I'm assuming your real question is "how can I take data in PHP and make a copy of that data available to Javascript". 我假设您真正的问题是“如何在PHP中获取数据并使该数据的副本可用于Javascript”。

There are two main approaches you could take: 您可以采用两种主要方法:

  1. Have your Javascript, when triggered, attempt to get information from the server via AJAX call. 触发Java脚本时,尝试通过AJAX调用从服务器获取信息。 That would be a separate PHP script and the JS would have to pass in some sort of ID or other information to help you figure out what it needs. 那将是一个单独的PHP脚本,而JS将必须传递某种ID或其他信息来帮助您确定它的需求。
    • Requires a separate PHP script and extra plumbing. 需要单独的PHP脚本和额外的管道。
    • Better when the amount of data is large 数据量大时更好
    • Better when there are a lot of these buttons and users won't use that many of them 当有很多这样的按钮并且用户不会使用那么多按钮时会更好
    • Forms the foundation of much fancier stuff later on 后来形成了许多更高级的东西的基础
  2. Embed the information into the HTML, and have the Javascript read it out. 将信息嵌入HTML中,并让Javascript读出。
    • Easier to do 容易做
    • Page is bigger 页面更大
    • May become a problem once you start doing it a lot 一旦开始做很多事情,可能会成为一个问题
    • You'll probably need to do this just a little bit even after AJAX gets used, to pass IDs and things. 即使使用了AJAX,您也可能只需要一点时间来传递ID和事物。

I'd suggest you try the "quick and dirty" way for the moment, just to get a feel for it. 我建议您暂时尝试“快速而肮脏”的方式,以期对此有所了解。 For example, in your PHP page: 例如,在您的PHP页面中:

<?php
/* ... */
$defaultMessage = "Hello world! Watch me contain single quotes (') and double quotes(\") and other things!";
/* ... */
?>
<button id="new_message" onclick="createMessage(<?= htmlentities(json_encode($defaultMessage))?>">New Message</button>

I'm not 100% sure on the escaping, but test with single and double quotes in the data to ensure nothing goes awry, and remember that you need to escape it one way to avoid breaking HTML, and again in another way to avoid breaking javascript. 我不确定转义是否100%,但是请对数据中的单引号和双引号进行测试,以确保所有内容都不会出错,并且请记住,您需要以一种避免转义HTML的方式对其进行转义,然后以另一种方式避免转义的方式进行转义JavaScript的。 Then in your JS file: 然后在您的JS文件中:

function createMessage(defaultMessage) {
    // ...
    textarea.value = defaultMessage;
    // ...
}

In this way you've put data from PHP into the HTML output, and then later (after the PHP script has stopped running) the user's browser gets the HTML and can can pull that data back out for whatever purpose it needs. 通过这种方式,您已经将来自PHP的数据放入HTML输出中,然后(在PHP脚本停止运行之后),用户的浏览器将获得HTML,并且可以出于所需的目的将数据拉回。

PHP is executed server side while javascript runs client side. PHP在服务器端执行,而javascript在客户端运行。 To pass variables or any other data between javascript and php you need to either call your server via ajax requests or (for static data) put the data into your page source to process it with javascript. 要在javascript和php之间传递变量或任何其他数据,您需要通过ajax请求调用服务器,或者(对于静态数据)将数据放入页面源中以使用javascript处理。 Anyway you need to convert the data on the server side to allow for processing. 无论如何,您都需要在服务器端转换数据以进行处理。 For example create an interface.php file containing something like the following: 例如,创建一个包含以下内容的interface.php文件:

<?php
  $mydata = array("username"=>"john");
  echo "window.serverdata=".json_encode($mydata).";";
?>

And then include it in your page: 然后将其包含在您的页面中:

<script type="text/javascript" src="interface.php"></script>
...
<script type="text/javascript">
  alert(serverdata.username);
</script>

Note that ajax requests are the de facto standard since you do not want to reload your page every few seconds. 请注意,ajax请求是事实上的标准,因为您不想每隔几秒钟重新加载一次页面。 The above mentioned method can be useful if you want to exchange static data. 如果要交换静态数据,上述方法可能会很有用。

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

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