簡體   English   中英

將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 
       }
  .....
}

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM