Javascript 如何在ajax调用中包含js文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2673592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include js file in ajax call?
提问by Anubhaw
I am calling a ajax method to update a div. It contains links and functions which require java script files. But these methods and functions are not getting called properly as java script files are not getting included through ajax call. For example, i am trying to call a light box function, but it gets redirected to different page and not in light box.
我正在调用 ajax 方法来更新 div。它包含需要 java 脚本文件的链接和函数。但是这些方法和函数没有被正确调用,因为 java 脚本文件没有通过 ajax 调用被包含在内。例如,我试图调用一个灯箱函数,但它被重定向到不同的页面,而不是在灯箱中。
Thanks in advance, Anubhaw Prakash
提前致谢, Anubhaw Prakash
回答by Kevin
The Ajax framework in prototype willproperly execute the text content of <script>tags, but will notimport new script files via <script src="somefile.js"/>. The only solution I came up with is to import all javascript files I need in the head of the page. That way the functions in the imported file are available to the inline javascript code executed in the Ajax response.
原型中的 Ajax 框架会正确执行<script>标签的文本内容,但不会通过<script src="somefile.js"/>. 我想出的唯一解决方案是在页面的头部导入我需要的所有 javascript 文件。这样,导入文件中的函数可用于在 Ajax 响应中执行的内联 javascript 代码。
回答by Daniel
I had a similar problem, where I did want to postload some javascript. What I did is separating loading the html-fragment and loading the script into two calls. For loading the script I call the following function (I have JQuery handling the ajax part):
我有一个类似的问题,我确实想后载一些 javascript。我所做的是将加载 html-fragment 和将脚本加载到两个调用中。为了加载脚本,我调用了以下函数(我让 JQuery 处理 ajax 部分):
function loadModule(name, callback) {
$.ajax({type: "POST"
, url: "/js/" + name
, dataType: "script"
, success: callback
});
}
回答by Vipin Jain
hey i found a way to add it....:)
嘿,我找到了添加它的方法....:)
NOTE- this is a synchronous process so you dont have to worry about that the script is loaded or not.... the script will always load the instance u call the function and you can start using the loaded script instantaneously..
注意-这是一个同步过程,因此您不必担心脚本是否已加载....脚本将始终加载您调用该函数的实例,您可以立即开始使用加载的脚本..
lets use these 2 functions
让我们使用这两个功能
1) first one is the ajax function to retrieve the values where async should be true to send the request synchronously
1) 第一个是 ajax 函数,用于检索 async 应该为 true 以同步发送请求的值
// AJAX FUNCTION
function loadXMLDoc(reqt,url,reqp,cfunc,async)
{
var xmlhttp;
try// code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
catch(err)// code for IE6, IE5
{
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E){}
}
}
if(!xmlhttp)
{
alert("error");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
cfunc(xmlhttp.responseText);
}
}
if(reqt=='GET')
{
url+=(reqp!=""?"?":"")+reqp;
xmlhttp.open("GET",url,(async?false:true));
xmlhttp.send();
}
else if(reqt=='POST')
{
xmlhttp.open("POST",url,(async?false:true));
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(reqp);
}
else
{
return false;
}
}
/*use this function
loadXMLDoc(reqt,url,reqp,function(response){
});
*/
2)then we use ajax to load the js file as string and then append it to the new script tag's innerHTML and then append it to the head section and one more thing to ensure file is already loaded i used the id of script tag as the path to the file which makes it really easy task to check for the duplicate...:)
2)然后我们使用ajax将js文件作为字符串加载,然后将其附加到新脚本标签的innerHTML,然后将其附加到head部分,还有一件事确保文件已经加载我使用脚本标签的id作为文件的路径,这使得检查重复项变得非常容易......:)
//add new script dynamically
function add_script(src)
{
if(!document.getElementById(src))
{
loadXMLDoc("GET",src,"",function(jsresp){
var head = document.getElementsByTagName("head")[0];
var script=document.createElement("script");
script.type='text/javascript';
script.id=src;
script.text=jsresp;
head.appendChild(script);
},true);
}
}
thanks for all help i used to get and will get from this site and its users for the development purposes...
感谢我过去和将来从本网站及其用户获得的所有帮助,用于开发目的...
regards VIPIN JAIN
问候VIPIN JAIN
回答by T.J. Crowder
I see you're using Ruby on Rails — does that mean you're using Prototype on the client? If so, Prototype's Ajax.Updaterwill ignore script tags that reference external files (it will evaluate script tags that have their contents inline). So to add those external files to your page, you'll have to hook into the process via the onSuccesscallback, look in the responseTextfor script tags with srcattributes, and handle those yourself. Once you've identified the relevant script tags and extracted their srcattributes, you can include them by dynamically adding the scripts as described in this articlefrom the unofficial Prototype & script.aculo.us wiki.
我看到您正在使用 Ruby on Rails — 这是否意味着您在客户端使用 Prototype?如果是这样,PrototypeAjax.Updater将忽略引用外部文件的脚本标签(它将评估具有内联内容的脚本标签)。因此,要将这些外部文件添加到您的页面,您必须通过onSuccess回调挂钩到流程中,查看responseText具有src属性的for 脚本标记,并自己处理这些文件。一旦您确定了相关的脚本标签并提取了它们的src属性,您就可以通过动态添加脚本来包含它们,如本文中来自非官方 Prototype & script.aculo.us wiki 的描述。
回答by bobince
<script>tags written to innerHTMLare not executed at write-time. You can do element.getElementsByTagName('script')to try to get hold of them and execute their scripts manually, but it's very ugly and not reliable.
<script>写入的标签innerHTML不会在写入时执行。您可以element.getElementsByTagName('script')尝试获取它们并手动执行它们的脚本,但它非常丑陋且不可靠。
There are tedious browser differences to do with what happens to a <script>element written to innerHTMLwhich is then (directly or via an ancestor) re-inserted into the document. You want to avoid this sort of thing: just don't write <script>?s to innerHTMLat all.
对于<script>写入的元素会发生什么innerHTML,然后(直接或通过祖先)重新插入到文档中,浏览器存在一些繁琐的差异。你想避免这种事情:根本不要写<script>?s innerHTML。
Then you also don't have to worry about executing scripts twice, which is something you never want to do with library scripts. You don't want to end up with two copies of a function/class that look the same but don't compare equal, and which hold hooks onto the page that don't play well with each other. Dynamically-inserted library scripts are a recipe for confusing failure.
然后你也不必担心执行脚本两次,这是你永远不想用库脚本做的事情。您不希望最终得到一个函数/类的两个副本,它们看起来相同但比较不相等,并且它们在页面上保留了彼此不能很好地配合的钩子。动态插入的库脚本是混淆失败的一个秘诀。
Much better to include your scripts statically, and bind them to page elements manually after writing new elements to the page. If you really need to you can have your AJAX calls grab a JSON object containing both the new HTML to add and a stringful of script to execute.
静态地包含您的脚本要好得多,并在将新元素写入页面后手动将它们绑定到页面元素。如果您真的需要,您可以让 AJAX 调用获取一个 JSON 对象,其中包含要添加的新 HTML 和要执行的一串脚本。
回答by SilentNot
May want to try running some prepatory javascript in the :before option to setup a variable with the correct files?
可能想尝试在 :before 选项中运行一些准备性 javascript 以使用正确的文件设置变量?
回答by Bob Gregor
- include static scripts on pages that need to use them (IE contain a lightbox, then include the lightbox script)
- Problem solved. Do not load scripts using AJAX
- Make necessary function calls to the static scripts using AJAX callbacks
- 在需要使用它们的页面上包含静态脚本(IE 包含灯箱,然后包含灯箱脚本)
- 问题解决了。不要使用 AJAX 加载脚本
- 使用 AJAX 回调对静态脚本进行必要的函数调用

