简体   繁体   中英

Adding JavaScript to document with PHP

Ok, so this should be easy right? 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.

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.

Here's a basic structure of what I'm trying to do:

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). But no alert window! Instead I get "alert('Hello')".

Other than that the code works fine but I can't get javascript to work. There must be some detail I'm missing. Any ideas????

You cannot run <script> tags by adding them through innerHTML . See this question: Can scripts be inserted with 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).

Second, even if you would insert a SCRIPT element in the document, initial parsing is already done and the alert would not be executed.

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.

I am using something like this to get Javascript code to work from ajax's responseText ;

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. 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.

PS: In my vision it is not a good idea to load javascript with ajax. 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.

There are plenty of Javascript libraries to do this for you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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