将ajax内容应用于元素后执行js函数

时间:2016-04-14 19:04:40

标签: javascript html ajax

我有一个js AJAX,它获取一些内容并将其插入名为content_holder的html元素中。我想在使用ajax更新内容后立即调用函数。我试图将On Pointer Up元素添加到已添加的内容中,但似乎它没有被执行。所以我希望有人在这里知道解决方案。 (我不使用jQuery)



<script>
&#13;
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{}
	
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分: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 
       }
  .....
}

希望有所帮助