2017-01-15 41 views
-2

如何在没有JQuery的情况下做到这一点?如何知道AJAX何时完成了原生JS的过程?

这里是我的代码:

我想是这样的:

xhr.finished { 
    alert(AJAX has finished it's process and the HTML has been updated); 
} 
+0

你必须做什么jQuery不会,注册一个'onreadystatechange'回调。 https://developer.mozilla.org/de/docs/Web/API/XMLHttpRequest – Thilo

+0

'onload'做了什么?谁提供的? – Thilo

+0

带上'fetch' API - 这将会变得更加美好... – lonesomeday

回答

0

你安装了错误的事件处理程序...尝试onreadystatechange。对于你的情况,我会建议增加一个回调函数您runScript功能:

function runScript(params, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', 'scripts.php', true); 
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState === XMLHttpRequest.DONE) { 
      callback(xhr.status, xhr.responseText); 
     } 
    }; 
    xhr.send(encodeURI(params)); 
} 

runScript('foo=bar', function finished(status, response) { 
    console.log('It is done...'); 
}); 
+0

onreadystatechange是如此最后十年... loadstart,进度,加载,超时,错误,放弃,加载事件是至少从2008年起使用XHR的方式 –