ajax用post方法傳遞參數


 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>JS</title>

    <style>

        #box{

            width:600px;

            height:200px;

            padding:20px;

            border:1px solid #999;

        }

    </style>

</head>

<body>

    <h1>ajax post方式傳遞參數</h1>

    <hr>

    Number1: <input type="text" id="num1"><br>

    Number2: <input type="text" id="num2"><br>

    <button onclick="loadHtml()">加載</button>

    <div id="box"></div>

    <script>

        function loadHtml(){

            //獲取表單中的數據

            var num1 = document.getElementById('num1').value;

            var num2 = document.getElementById('num2').value;

 

            //實例化XMLHttpRequest對象

            if(window.XMLHttpRequest){

                //非IE 

                var xhr = new XMLHttpRequest();

            }else{

                //IE 6

                //var xhr = new ActiveXObject('Microsoft.XMLHTTP');

                var xhr = new ActiveXObject('Microsoft.XMLHTTP');

            }

            //給xhr綁定事件.檢測請求的過程

            xhr.onreadystatechange = function(){

                console.log(xhr.readyState);

                //如果成功接收到並響應

                if(xhr.status == 200 && xhr.readyState == 4){

                    document.getElementById('box').innerHTML = xhr.responseText;

                }

            }

            //進行請求的初始化

            xhr.open('post','js.php',true);

            //設置請求頭

            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

            //正式發送請求

            xhr.send('n1='+num1+'&n2='+num2);

        }

    </script>

</body>

</html>


免責聲明!

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



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