XMLHttpRequest 在该代码中做了什么

What does XMLHttpRequest do in that code

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

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

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

这是对 AJAX 请求的引用。 参见 more at the MDN site

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

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

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();

希望对您有所帮助!

编码愉快!

你好,我不是很擅长解释,但我会尽量详细解释,因为我看到并理解了这一点。

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();

希望这对您有所帮助,祝您好运!