gpt4 book ai didi

javascript - 如何返回xmlHttp请求状态?

转载 作者:行者123 更新时间:2023-11-28 17:46:11 26 4
gpt4 key购买 nike

我想知道如何在发送 xmlHttp 请求后验证其状态。我该如何去做呢?谢谢。

function sendRequest(){
//get refresh access token
var accessToken = 'xxx';
//get user_id
var userid = document.getElementById('userid').value;
//get request_token
var requestToken = document.getElementById('requestToken').value;

//insert database
var xmlHttp = new XMLHttpRequest();
var url="database.php";
var parameters = "accessToken=" + accessToken + "&userid=" + userid + "&requestToken=" + requestToken ;
xmlHttp.open("POST", url, true);

//send request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);

//check status
if(xmlHttp.status == Ok){
alert('success!');
}else {
alert('error');
}

}

最佳答案

<!DOCTYPE html>
<html>
<body>

<h2>Using the XMLHttpRequest object</h2>

<button type="button" onclick="loadXMLDoc()">Change Content</button>

<p id="test"></p>

<script>


function sendRequest(){
//get refresh access token
var accessToken = 'xxx';
//get user_id
var userid = document.getElementById('userid').value;
//get request_token
var requestToken = document.getElementById('requestToken').value;


var xmlHttp = new XMLHttpRequest();
var xhttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML =
this.responseText;
}
};
//insert database
var url="database.php";
var parameters = "accessToken=" + accessToken + "&userid=" + userid + "&requestToken=" + requestToken ;
xmlHttp.open("POST", url, true);

//send request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);



}

</script>

</body>
</html>

关于javascript - 如何返回xmlHttp请求状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46679182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com