[英]AJAX to request another javascript or function from the server
As we know that AJAX is used to request a web-part in HTML format from the server. 我们知道AJAX用于从服务器请求HTML格式的Web部件。 Is it possible to request a script containing functions using AJAX? 是否可以使用AJAX请求包含函数的脚本?
Yes you can load a javascript via ajax 是的,您可以通过ajax加载JavaScript
http://api.jquery.com/jQuery.getScript/ http://api.jquery.com/jQuery.getScript/
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
Also you could try something like this as mentioned in( how to run javascript in html loaded via ajax ): 你也可以尝试这样的东西( 如何在通过ajax加载的html中运行javascript)中提到的:
require("extra.js", function () {
functionDefinedInExtraJS();
});
//Sample require function:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
One other way would be to use eval() function and convert a string reply into working javascript code. 另一种方法是使用eval()函数并将字符串回复转换为工作的javascript代码。
Here's an example how to use eval() to accomplish what you need: 这是一个如何使用eval()来完成你需要的例子:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(xmlhttp.responseText);
// you can use whatever functionw as returned from the server from this line on :)
}
}
xmlhttp.open("GET","your-server-page-url",true);
xmlhttp.send();
Is it possible to request a script containing functions using AJAX? 是否可以使用AJAX请求包含函数的脚本?
Yes, it is possible. 对的,这是可能的。 And those functions could be executed on the client. 这些功能可以在客户端上执行。 For example with jQuery you even have a function that allows you to perform such request: $.getScript
. 例如,使用jQuery,您甚至可以使用一个允许您执行此类请求的函数: $.getScript
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.