在我的应用程序中,我使用 Ajax 导航和 jQuery post。
场景:
假设用户输入 URL 并加载索引页面。现在他想要转到他的个人资料页面(假设他之前已经登录)。单击“我的个人资料”链接,将执行 jQuery post 并在主 div 中返回 html 结果。
我遇到的问题:
配置文件页面有自己的 profile_functions.js 文件,其中包含与配置文件相关的 js 函数。在 jQuery 帖子中,我进行了检查,因此当请求用户配置文件页面时,它会在执行 jQuery 之前加载 profile_functions.js邮政。 (使用 document.getElementsByTagName("head")[0].appendChild(file);
附加它)
在 profile_functions.js 中,我有一些 jQuery 插件,需要使用 $(document).ready(function(){ });
进行初始化。它被放置在 HTML 结果中。我注意到的问题是,有时 jQuery post 结果的检索早于 .js 文件的加载完成,所以我收到一个错误,当然 jQuery 插件不起作用。
所以我的问题是:使用 jQuery post,加载 post result-html 代码所需的新 .js 文件的最佳且成功的方法是什么?
编辑:根据要求,这是我的代码:
//Loads the new JS
function loadjscss(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (typeof fileref!="undefined"){document.getElementsByTagName("head")[0].appendChild(fileref);}
}
//Part of function that loads the new page
function ajax_menu_nav(requested_page) {
if(requested_page=='profile_page'){
loadjscss("/static/profile_functions.js", "js");
}
$.post("/ajax_menu.php",
{
rp:requested_page,
rand:Math.random()
} ,
function(rd) {
$('#main').html(rd.tpl);
}, "json"
);
}
现在结果 HTML 代码包含以下内容:
$(document).ready(function(){ function_a(); });
其中 function_a() 来自 profile_functions.js 文件。
最佳答案
我认为问题在于 function_a 在 DOM 准备好时被调用,因此在脚本加载之前被调用。您应该在加载脚本时在回调中自己调用它。
关于javascript - jQuery post 之后加载新的 javascript 文件的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868786/