javascript - 使用 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")); }
解决方案
所以这就是我在第一种情况下使用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;
}
}
推荐阅读
- java - Webflux 安全登录失败处理程序不起作用
- java - 为什么 TreeSet 在添加新元素之前不比较所有元素?
- mysql - 如何在 Laravel Eloquent 中使用 MIN 和 MAX sql 查询
- java - 使用 Jenkins 运行时无法识别 ole 流错误
- android - 如何打印到热敏蓝牙打印机?
- c# - VB 到 C# 等效的拆分函数
- python - Python - 如何设置法语语言环境?
- java - Spring-JPA - 如何从自联接表中输出有限字段
- mongodb - 无法使用 statefulset 和 sidecar 为 mongodb 创建只读副本
- chef-infra - 当数据包中的某些内容发生更改而不登录厨师客户端机器时如何重新运行食谱