开发者

ajax. how to invoke javascript code from requested html file

i have the index.html page.

Inside that page i have javascript code that makes a button to evoke ajax request for the other.html to be shown inside a div in index.html .

The other.html have nothing else but a div ( that contains the content ) and some javascript code.

The other.html loads normally inside the index.html but the javascript code does not work.

Anyone know why is this happening?

Thank you.

( the javascript code is as simple as an alert("hello") message ).

code:

index.html:

<html>
<head>
<script src=main.js></script>
</head>

<body>
<div id="to_change">bla bla bla</div>
<div id="button">click me</div>
</body>
<html>

main.js:

...
...
function sendRequest()
{
    request.open("GET","other.html",true);
    request.onreadystatechange = function(){
        if(request.readyState == 4 && request.status == 200){

        开发者_运维百科    var response = request.responseText;

            if(response) {
                document.getElementById("to_change").innerHTML = response;
            }
        }
    }
    request.send(null);
}

....button.click(...sendRequest...);
...
...

other.html

<script type=...>alert("hello");</script>
<div>text text text text</div>


javascript is loading but function call is not happening.

You are not calling the functions in any event.

<BODY onLoad="alert('hello world!')">

Like this try to call the function . On any event you want


Make sure to remove the enclosing '<doctype...>', '<html>', and '<body>' tags from the "other.html" file, in case they are present.


You could try running the scripts manually:

// ...
if (response) {
  var toChange=document.getElementById("to_change"), scripts, i;
  toChange.innerHTML = response;
  scripts = toChange.getElementsByTagName('script');
  for (i=0; i<scripts.length; i++) {
    eval(scripts[i].innerHTML);
  }
}

Of course, eval is evil, so use at your own risk...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜