2016-04-14 102 views
0

我有一個js AJAX獲取一些內容並將其插入到名爲content_holder的html元素中。我想在使用ajax更新內容後立即調用一個函數。我試圖將<script>元素放入添加的內容中,但看起來好像沒有被執行。所以我希望這裏有人會知道這個解決方案。 (我不使用jQuery)將ajax內容應用到元素後執行js函數

function ajax(instruction, push, url, callback){ 
 
\t 
 
\t var xmlhttp; // the object for the httprequest 
 
\t 
 
\t if (window.XMLHttpRequest) { 
 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
 
      xmlhttp = new XMLHttpRequest(); 
 
     } else { 
 
      // code for IE6, IE5 
 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
 
     } 
 
\t \t 
 
\t \t 
 
     xmlhttp.onreadystatechange = function() { // every time the readystate changes 
 
\t \t 
 
      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) 
 
\t \t \t 
 
\t \t \t  var content = xmlhttp.responseText + "<script>ajaxDone();</script>"; 
 
\t \t \t 
 
\t \t \t \t callback(content); // goes to the callback function (from the argument "callback") and then passes the xmlhttp 
 
      } 
 
\t \t \t 
 
     }; 
 
     xmlhttp.open(instruction,url,true); // sends a the var q to the next php file 
 
     xmlhttp.send('');    // Sends the request 
 
\t 
 
\t 
 
\t  if(push == true){ // Change the link to the url of the ajax with 
 

 
\t \t  var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on 
 
\t \t 
 
\t \t 
 
\t \t  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 \t (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY) \t \t 
 
\t \t \t  return; // exit's the function 
 
\t \t  }else{} 
 
\t \t 
 
\t \t 
 
      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 
 

 
      
 
\t \t window.history.pushState({path:urlPath},'',newLink); // the push 
 
\t \t 
 
     } \t 
 
\t \t else{} 
 
\t 
 
}
<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>

+1

您需要將您的(相關)代碼添加到問題中。 – Andy

回答

1

看看這個話題:How to make an AJAX call without jQuery?

你可以像水木清華:

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

希望它可以幫助

+0

感謝它現在的作品!我已經知道它,並有一個功能,這也包括我的回調函數。所以我只是添加了我想在回調之後執行的新功能。現在我感覺有點愚蠢 –

相關問題