js發送請求給服務端


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<script type="text/javascript">
function post(){
    var postData = {
    "username": "13321503898",
    "password": "a123456",
    "imsi":"wzy - 加載的時候執行"
    };
    var url = "http://10.20.49.10/appall/get/js/post/data";
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send(JSON.stringify(postData));
}


</script>

<input type="button" value="觸發請求" onclick="post()" style="width:200px;height:200px;font-size:30px"/><br><br>


<script>post()</script>

</body>
</html>
<html>
<meta charset="GBK">
<body>

<script type="text/javascript">
function post(){
    var postData = {
    "username": "13321503898",
    "password": "a123456",
    "imsi":"wzy"
    };

    var url = "http://11.20.49.10appall/get/js/post/data";

    var xhr = new XMLHttpRequest();

    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    xhr.onreadystatechange = function(){

        var XMLHttpReq = xhr;
        /**
            XMLHttpReq.readyState
         0: 請求未初始化
         1: 服務器連接已建立
         2: 請求已接收
         3: 請求處理中
         4: 請求已完成,且響應已就緒
        **/
        if (XMLHttpReq.readyState == 4) {
            if (XMLHttpReq.status == 200) {
                var data = XMLHttpReq.responseText;
                alert(data);
                console.log(data);
                var json = JSON.parse(JSON.parse(data));
            }else if(XMLHttpReq.status == 100){

            }else if(XMLHttpReq.status == 300){

            }else if(XMLHttpReq.status == 400){

            }else if(XMLHttpReq.status == 500){

            }else if(XMLHttpReq.status == 0){
                /** 0不是http協議的狀態,關於XMLHttpReq.status的說明:
                1、If the state is UNSENT or OPENED, return 0.(如果狀態是UNSENT或者OPENED,返回0)
                2、If the error flag is set, return 0.(如果錯誤標簽被設置,返回0)
                3、Return the HTTP status code.(返回HTTP狀態碼)
                第一種情況,例如:url請求的是本地文件,狀態會是0
                第二種情況經常出現在跨域請求中,比如url不是本身網站IP或域名,例如請求www.baidu.com時
                第三種,正常請求本站http協議信息時,正常返回http協議狀態值
                **/
            }

        }
    };

    xhr.send(JSON.stringify(postData));
}


</script>
<!--
變量string_a:<input type="text" value="" id="string_a"/><br><br>
變量string_b:<input type="text" value="" id="string_b"/><br><br>

變量list_a:<input type="text" value="" id="list_a"/><br><br>
變量list_b:<input type="text" value="" id="list_b"/><br><br>
 -->
<input type="button" value="觸發請求" onclick="post()" style="width:200px;height:200px;font-size:30px"/><br><br>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM