XMLHttpRequest 在该代码中做了什么

What does XMLHttpRequest do in that code

本文关键字:什么 代码 XMLHttpRequest      更新时间:2023-09-26

我是Javascript的初学者,我想了解XMLHttpRequest方法的作用。

这是我正在阅读的代码,我想知道是否有人可以解释它在做什么:

var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();

嗨,我不太擅长解释,但我会尝试详细解释这一点,因为我看到并理解了这一点。

XMLHttpRequest 是一个对象。它用于与服务器交换数据。因此,通过使用它,您可以将一些数据发送到服务器上的脚本(请求),并从中获取一些数据(响应)。该响应数据可以立即显示在页面上,而无需重新加载页面。所以这个过程调用 AJAX。

我会将您提供的代码读取为

//define a variable 
var xhttp;
/*assign a XMLHttpRequest object to this variable
check if the global object window has a XMLHttpRequest object already
if not and user have a newer browser, create one (new XMLHttpRequest - for           IE7+, Firefox, Chrome, Opera, Safari browsers) or user have an older browser (ActiveXObject("Microsoft.XMLHTTP") - for IE6, IE5 browsers)
xhttp.open method specifies the type of request(method GET, Script on server,    asynchronous)
xhttp.send method sends the request to a server*/
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new     ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();

但是您还必须检查XMLHttpRequest对象的readyState属性。

xmlhttp.onreadystatechange = function() {
    //4: request finished and response is ready
    //200: "OK"
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //display of returned data from the server
        //it is available in this property - xmlhttp.responseText
    }
}

代码的整个和平应该看起来像:

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();                     // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //display of returned data from the server
        //jquery example
        $('div').html(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", "script.php", true);
xmlhttp.send();

希望这有帮助,祝你好运!

它是对 AJAX 请求的引用。在 MDN 网站上查看更多信息。

简而言之,它正在向脚本发送GET请求.php。

XMLHttpRequest 是一个用于发出 AJAX 请求的 JavaScript 对象。我不完全确定代码是否正确。通常,您创建XMLHttpRequest对象的实例。然后检查窗口就绪状态以发出请求。最后,您提出请求。这是一个例子:

var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
        callback(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

我希望这有所帮助!

祝您编码愉快!