使用 xmlhttprequest 响应作为函数
我正在尝试检索包含函数的 js 文件。我希望能够存储它,并在单击按钮时在我的页面中调用它。我包含了我的测试代码。我得到了响应;我可以通过更改 div 以显示文件中的文本来测试它。
是否可以以某种方式存储 JS 函数?我希望能够向该页面添加另一个按钮,该按钮将触发存储在外部文件(alert.js)上的函数。
<html>
<head>
<script type="text/javascript">
function loadJS() {
var ajax;
ajax = new XMLHttpRequest();
ajax.onreadystatechange=function() {
if (ajax.readyState==4 )
{
document.getElementById("myDiv").innerHTML=ajax.responseText;
}
}
ajax.open("GET","scripts/alerts.js",true);
ajax.send();
}
</script>
</head>
<body>
<button type="button" onclick="loadJS()">Change Content</button>
<div id="myDiv">
</div>
</body>
</html>
I am trying to retrieve a js file which contains a function. I want to be able to store it, and call it within my page when i click a button. I included my test code.I got the response working; I was able to test it by changing the div to dusplay the text within the file.
Is it possible to store the JS functions somehow? I want to be able to add another button to this page that would trigger a function stored on the external file (alert.js).
<html>
<head>
<script type="text/javascript">
function loadJS() {
var ajax;
ajax = new XMLHttpRequest();
ajax.onreadystatechange=function() {
if (ajax.readyState==4 )
{
document.getElementById("myDiv").innerHTML=ajax.responseText;
}
}
ajax.open("GET","scripts/alerts.js",true);
ajax.send();
}
</script>
</head>
<body>
<button type="button" onclick="loadJS()">Change Content</button>
<div id="myDiv">
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您从 AJAX 获取 JavaScript,请通过
eval()
运行它来处理它。 JS 中的任何函数声明都可以被其他按钮等使用。If your getting JavaScript from AJAX, run it through
eval()
to process it. Any function declarations in the JS can then be used by other buttons etc.