首页 > 解决方案 > 使用 AJAX 从 HTML 调用 .js 文件

问题描述

这个 js 在 index.html 之间"<script type="text/javascript">"

function callanular() {

        peticion_http = new XMLHttpRequest();

        peticion_http.onreadystatechange = showContent;

        peticion_http.open('GET', 'anular.js', true); 
        peticion_http.send(null);                       


        function showContent() {

            if(peticion_http.readyState == 4) {

                if(peticion_http.status == 200) {

                    document.getElementById("notice").innerHTML=peticion_http.responseText;

                }
                else
                    document.getElementById("notice").innerHTML="ERROR "+peticion_http.status;
            }
        }
    }

我有 index.html HTML 代码,希望在 id=notice 的 div 上显示框

<div id="notice"></div>
<input type="submit" value="RESTRICTED ACCESS" onclick="callanular()">

在我创建了 anular.js 的同一个文件夹中,我想显示一个带有 text 的简单框,在这种情况下,我只有一个警报知道它正在工作。

window.onload = function() {
    return (alert("asdasdsa"));
}

无论我写什么,我都只能收到字面上的代码。例如

window.onload = function() {return (alert("asdasdsa")); }

标签: javascripthtmljqueryajax

解决方案


所以这就是我在第一种情况下使用Jquery ,在第二种情况下使用AJAX来解决它的方法。

第一个案例

index.html 上的 Javascript 代码

function callanular() {

        $.getScript("anular.js", function(){
            //You can write an alert or something
            //In my case it wasn't necessary.
        });
    }

anular.js 内容

document.getElementById("notice").innerHTML = "<div id='nopul' onclick='getText()'>YOU SHOULDN`T PRESS THIS BUTTON</div><br>";

回到我得到的 index.html:

<div id="notice"></div> //here anular.js is going to show the div box
<input type="submit" value="RESTRICTED ACCESS" onclick="callanular()">

在那一点上,它按我的意愿工作得很好。所以我添加了 AJAX 来从 txt 文件中获取文本,只需调用

XMLHTTPRequest();

peticion_http.open('GET', 'text.txt', true);

-

第二种情况 anular.js 文件

<div id='nopulses' onclick='getTexto()'>YOU SHOULDN`T PRESS THIS BUTTON</div><br>

index.html javascript 代码

        peticion_http = new XMLHttpRequest();

        peticion_http.onreadystatechange = showContent;

        peticion_http.open('GET', 'anular.js', true);  
        peticion_http.send(null);                       

        function muestraContenido() {

            if(peticion_http.readyState == 4) {

                if(peticion_http.status == 200) {

                    document.getElementById("notice").innerHTML=peticion_http.responseText;

                }
                else
                    document.getElementById("notice").innerHTML="ERROR 404 Not Found "+peticion_http.status;
            }
        }


推荐阅读