Javascript没有在php函数中运行 [英] Javascript isn't running in php function
问题描述
我有2个php文件。文件1包含文件2.文件1从文件2调用php函数。在php函数内部有一堆html。该html完美的作品。在函数结尾我有这个javascript ....
< script type =text / javascript>
alert('hello');
< / script>
这个javascript没有提示hello。
我做错了什么?
预先感谢您。
编辑: 新的问题,因为我最后一个了。
理论上,下面的代码可以正常运行吗? (是/否)
<?php function AlertHelp(){
?>< script>
alert('help');
< / script><?
AlertHelp();
?>
你给了。
我的假设是,你不是通过PHP的 include
, require
, include_once
或 require_once
函数,但事实上使用AJAX加载该页面的内容。
如果是这种情况,那么我还会假设您正在使用 innerHTML
将内容放在页面上。
突然间,解决方案显而易见:< script>
code> innerHTML 不会被分析和运行。你可以这样做:
//假设`result`是包含AJAX响应和elem的变量元素它在
elem.innerHTML =结果; //这不会改变
result.match(/< script [^>] *>([\ s \ S] *?)< \ / script> / i,function (m){eval(m [1]);});
请注意,应避免
Where am I going wrong with my programming logic here?
I have 2 php files. File 1 includes File 2. File 1 calls a php function from File 2. Inside the php function there is a bunch of html. The html works perfectly. At the end of the function I have this javascript....
<script type="text/javascript">
alert('hello');
</script>
This javascript isn't alerting "hello". What am I doing wrong?
Thank you in advance.
EDIT: New question because I skrewed the last one up.
In theory would the code below run properly? (yes/no)
<?php function AlertHelp(){
?><script>
alert('help');
</script><?
AlertHelp();
?>
Long shot on a wild guess here with the limited information you gave.
My assumption is that you are not "including" the file via PHP's include
, require
, include_once
or require_once
functions, but are in fact using AJAX to load in the page's content.
If this is the case, then I shall also assume you're using innerHTML
to put the content on the page.
Suddenly the solution is obvious: <script>
tags added by innerHTML
are not parsed and run. You could probably do something like this:
// assume `result` is the variable containing the AJAX response and `elem` the element it goes in
elem.innerHTML = result; // this doesn't change
result.match(/<script[^>]*>([\s\S]*?)<\/script>/i,function(m) {eval(m[1]);});
Please note however that eval
should be avoided if possible. Consider redesigning your layout to use callbacks instead.
这篇关于Javascript没有在php函数中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!