简体   繁体   English

php代码中的JavaScript脚本标签

[英]JavaScript script tag inside php code

I have one page (parent) which opens a second page via popup (child) 我有一个页面(父页面),该页面通过弹出窗口(子窗口)打开了第二个页面

On the second page I have the following PHP code which gets the value of an HTML element from the parent page: 在第二页上,我具有以下PHP代码,该代码从父页面获取HTML元素的值:

 $var=print_r("<script type='text/javascript'>var x=window.opener.document.getElementsByName('name1');document.write(x[0].value)</script>",true);   

When I echo the variable $var I get exactly what I expect. 当我回显变量$var我得到的正是我所期望的。 Thus: 从而:

echo "test=" . $test;

... prints for example "Expenses" on the page. ...在页面上打印例如“费用”。

So far so good. 到现在为止还挺好。

The problem is when I try to write this variable to a file like: 问题是当我尝试将此变量写入文件时,例如:

$f=fopen("/mylog.txt","w+");
fwrite($f, $test);
fclose($f);

... then , instead of the actual value of $test (eg Expenses), ...然后,而不是$test的实际值(例如Expenses),

I get the whole script tag in my logfile, thus: 我在日志文件中得到了整个脚本标签,因此:

<script type='text/javascript'>var x=window.opener.document.getElementsByName('name1');document.write(x[0].value)</script>

Assuming that print_r with 'true' parameter returns the value to my $test variable, why is it writing the exact script tag to the logfile? 假设带有'true'参数的print_r将值返回给我的$test变量,为什么将确切的脚本标记写入日志文件?

How can I overcome this? 我该如何克服?

When you echo the value to a browser, it will run the JavaScript and display the result. 当您将值echo显到浏览器时,它将运行JavaScript并显示结果。

When you save it to a file, the JavaScript isn't executed. 将其保存到文件时,不会执行JavaScript。

In both cases, the full script is output, but the browser is actually running the script, whereas your text editor won't. 在这两种情况下,都将输出完整脚本,但是浏览器实际上正在运行脚本,而文本编辑器则不会。

Send your data which is on the client to the server. 将客户端上的数据发送到服务器。 You can use Ajax (shown below) or a form. 您可以使用Ajax(如下所示)或表单。

$.post('myPHPfile.php',{name:window.opener.document.getElementsByName('name1')});

myPHPfile.php myPHPfile.php

$test=$_POST['name'];
$f=fopen("/mylog.txt","w+");
fwrite($f, $test);
fclose($f);

OK , I accomplished the desired result by altering the url-string which calls the 2nd page with an extra variable (the desired one) and then , via $_GET , I retrieve this value and can print it without problems to my logfile. 好的,我通过更改URL字符串来实现期望的结果,该URL字符串使用一个额外的变量(期望的变量)来调用第二页,然后通过$ _GET检索此值并将其打印到我的日志文件中而不会出现问题。

Many thanks guys to all of you for the quick responses :) 非常感谢你们大家的快速回复:)

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

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