Ajax不执行其他页面javascript [英] Ajax does not execute other page javascript

查看:78
本文介绍了Ajax不执行其他页面javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I been researching for a long time and i'm so confused I read that you have to use the eval() function so plain ajax can recognize and execute the JavaScript on the other page I read thru a lot of sites but there is rarely no info on this or no examples that makes sense to me so can any one add the right code to my code to get this to work. I'm a visual learner.







index.php







<script>
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
    if(xhr.readyState === 4){
        document.getElementById('ajax').innerHTML= xhr.responseText;
    }
};
xhr.open('POST','x.php');

function startAjax(){
    xhr.send();
document.getElementById('hide_button').style.display= 'none';
    }
    </script>
    <body>
    <button id='hide_button' onclick='startAjax()'>Start</button>
    <div id='ajax'></div>
    </body>







x.php







<script>
alert('js is executed');
</script>

<h1>Radom text</h1>





我有什么尝试过:



我一直在许多网站上询问但是没有人愿意帮助我,就像他们不知道该怎么做或他们不喜欢修改我的代码以显示如何完成此操作。代码工作它只是不执行其他页面调用x.php上的js。



What I have tried:

I keep asking on many sites but nobody wants to help me out it's like they don't know how to do this or They don't modify my code to show how this can be done. The code works it's just not executing the js on the other page call x.php.

推荐答案

参考这个

Page1

refer this
Page1
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var response = xhr.responseText; 
                document.getElementById('ajax').innerHTML = response;
                setTimeout(function () {
                    var script = document.getElementById('ajax').getElementsByTagName('script')[0];
                    if (script) {
                        var js = script.innerText;
                        eval(js);
                    } 
                }, 100)
                
            }
        };
        xhr.open('get', 'htmlpage2.html');

        function startAjax() {
            xhr.send();
            document.getElementById('hide_button').style.display = 'none';
        }
    </script>
</head>
<body>
    <button id='hide_button' onclick='startAjax()'>Start</button>
    <div id='ajax'></div>
</body>


</html>





Page2



Page2

<script>
    alert('js is executed');
</script>

<h1>Radom text</h1>


这篇关于Ajax不执行其他页面javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆