简体   繁体   English

使用PHP向文档添加JavaScript

[英]Adding JavaScript to document with PHP

Ok, so this should be easy right? 好的,这应该很容易吧? test.php: test.php:

function some_javascript() {
        echo "Hello";
        echo "<script type='text/javascript'>alert('Hello')<script>";
}

and you'll get an alert window when you try to load your test.php. 当您尝试加载test.php时,您将看到一个警报窗口。

I must be missing something because I can't get this to work using a modal window as target and an AJAX request via post. 我必须缺少一些东西,因为我无法使用模式窗口作为目标以及通过post进行AJAX请求来使其正常工作。

Here's a basic structure of what I'm trying to do: 这是我要执行的操作的基本结构:

index.html: index.html:

<html>
<head>
<style>
 #modal {
    visibility:hidden;
 }
</style>
</head>
<body>
    <div id="modal">
    </div>
    <button onclick="call_ajax();">Call Ajax</button>
</body>
</html>

call_ajax() sets modal visibility to "visible" and its innerHTML to response text from test.php(I don't write code because I don't seem to have problems here; text is sent just fine (I get "hello") and post data sent is processed as needed). call_ajax()将模式可见性设置为“ visible”,并将其innerHTML设置为响应来自test.php的文本(我不编写代码,因为这里似乎没有问题;文本发送很好(我得到“ hello”))并根据需要处理发送的发布数据)。 But no alert window! 但是没有警报窗口! Instead I get "alert('Hello')". 相反,我得到“ alert('Hello')”。

Other than that the code works fine but I can't get javascript to work. 除此之外,代码工作正常,但我无法使javascript工作。 There must be some detail I'm missing. 我一定缺少一些细节。 Any ideas???? 有任何想法吗????

You cannot run <script> tags by adding them through innerHTML . 您不能通过innerHTML添加<script>标记来运行它们。 See this question: Can scripts be inserted with innerHTML? 看到这个问题: 脚本可以与innerHTML一起插入吗?

echo "<script type='text/javascript'>alert('Hello')<script>";

Should be 应该

echo "<script type='text/javascript'>alert('Hello')</script>";

Also as someone posted below me, scripts cannot be run in this way. 同样,有人张贴在我下面,脚本无法以这种方式运行。

First, script code cannot be inserted as HTML, it will show as such (and it did). 首先,脚本代码不能作为HTML插入,它会这样显示(确实如此)。

Second, even if you would insert a SCRIPT element in the document, initial parsing is already done and the alert would not be executed. 其次,即使您要在文档中插入SCRIPT元素,初始分析也已经完成,并且警报不会执行。

What you can do is to parse the script code and eval it: 您可以做的是解析脚本代码并进行评估:

<!DOCTYPE html>
<html>
<head>
    <style>
        #modal {
            visibility:hidden;
        }
    </style>
    <script type="text/javascript">
        function call_ajax() {
            var ajaxData = "Hello\n<script type='text/javascript'>alert('Hello')<\/script>";
            var scriptStartPos = ajaxData.indexOf("<script type='text/javascript'>");
            if(scriptStartPos >= 0) {
                var scriptPos0=scriptStartPos+31;
                var scriptEndPos= ajaxData.indexOf("<\/script>", scriptPos0);
                if(scriptEndPos >= scriptPos0) {
                    eval(ajaxData.substring(scriptPos0,scriptEndPos));
                }
            }
        }
</script>
</head>
<body>
<div id="modal">
</div>
<button onclick="call_ajax();">Call Ajax</button>
</body>
</html>

Please notice that i used un-escaped single quotes in this case. 请注意,在这种情况下,我使用了不转义的单引号。

Basically Ajax Request won't load Javascript code. 基本上, Ajax Request不会加载Javascript代码。

I am using something like this to get Javascript code to work from ajax's responseText ; 我正在使用类似的东西来从ajax的responseText获取Javascript代码;

Javascript : Javascript:

//pseudo function :
function call_ajax() {
  var ajaxResponse = "some data you have received with ajax"; 

  var div = document.createElement("div");
  div.innerHTML = ajaxResponse;
  var script = div.getElementsByTagName("script");
  for(var i=0; i < script.length; i++) {
    try{eval(script[i].innerHTML)}catch(ex){alert(ex)};
  }
};

This code will create a blank div element, where it's innerHTML will be data loaded with ajax. 这段代码将创建一个空白的div元素,其中的innerHTML将是用ajax加载的数据。 Javascript will transform your simple text to html nodes, then you can find if response contains Javascript code, by finding "script" tags, then just try to eval the javascript code to execute the code, now you're done. Javascript会将您的简单文本转换为html节点,然后您可以找到响应是否包含Javascript代码,方法是查找“ script”标签,然后尝试评估javascript代码以执行该代码,到此完成。

PS: In my vision it is not a good idea to load javascript with ajax. PS:在我看来,用ajax加载javascript不是一个好主意。 Look what if you do two ajax requests to the same javascript code : it will load the same code twice, so the code may become buggy because of this. 看一下,如果您对相同的javascript代码执行两个ajax请求:它将加载相同的代码两次,因此该代码可能因此成为错误的程序。

There are plenty of Javascript libraries to do this for you. 有很多Javascript库可以为您完成此操作。

Try lazyload: https://github.com/rgrove/lazyload 尝试lazyload: https : //github.com/rgrove/lazyload

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

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