我是Javascript的初學者,我想了解XMLHttpRequest的方法。XMLHttpRequest在該代碼中做了什麼
這是我讀的代碼,我想知道,如果有人可以解釋它是做什麼:
var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
我是Javascript的初學者,我想了解XMLHttpRequest的方法。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();
但你必須檢查以及
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
}
}
XMLHttpRequest對象的readyState屬性代碼的整個和平應該像我讀你提供的代碼:
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請求的參考。 見more at the MDN site。
簡而言之,它發送一個GET請求到script.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();
我希望有幫助!
快樂編碼!