在将ajax内容应用到元素后执行js函数
Execute js function after ajax content have been applied to an element
我有一个js AJAX,它获取一些内容并将其插入到一个名为content_holder的html元素中。我想在使用ajax更新内容后立即调用一个函数。我曾尝试将<script>
元素放入添加的内容中,但它似乎没有被执行。所以我希望这里有人能知道解决这个问题的办法。(我没有使用jQuery)
function ajax(instruction, push, url, callback){
var xmlhttp; // the object for the httprequest
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() { // every time the readystate changes
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done)
var content = xmlhttp.responseText + "<script>ajaxDone();</script>";
callback(content); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
}
};
xmlhttp.open(instruction,url,true); // sends a the var q to the next php file
xmlhttp.send(''); // Sends the request
if(push == true){ // Change the link to the url of the ajax with
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)
return; // exit's the function
}else{}
var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file
window.history.pushState({path:urlPath},'',newLink); // the push
}
else{}
}
<p><a href="?p=toplists" onclick="if(useAjax == true){ ajax('GET', true, 'toplists.php', function(content){ document.getElementById('content_holder').innerHTML = content; }); return false;}">Top Lists</a></p>
<div id="content_holder"></div>
看看这个主题:如何在没有jQuery的情况下进行AJAX调用?
你可以这样做:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
//here you call whichever function you want
}
.....
}
希望它能帮助
相关文章:
- Meteor:插入集合后如何执行JS
- 如何在Odoo 9中执行JS文件中的函数
- 匿名自执行js函数内部的全局变量在外部仍然可用
- NumericTextBox-当用户键入数字时执行JS计算.能做到吗
- 引导:响应式设计-当窗口大小从980px调整到979px时执行JS
- 对页面上的所有ID执行JS功能
- 从浏览器访问页面时执行js函数's后退按钮
- 源代码未完全执行.(JS)
- 在执行JS脚本后监视对DOM的更改
- 在表单同步提交后执行 js 吗?
- 在 ubuntu 14.04 VPS 上执行.js文件错误
- 从PHP插入时在MongoDB上执行JS
- 在将ajax内容应用到元素后执行js函数
- Windows Phone浏览器控件执行JS函数来替换src属性
- 到达新页面后执行js
- 用C#在Win 8.1 Chakra中执行JS的一个失败的最小例子
- 在sharepoint显示模板中执行JS
- 在Bootstrap popover内部执行JS
- 从引导程序popover内容内部执行js
- 顺序执行js