<!DOCTYPE html>php
<html lang="en">html
<head>ajax
<meta charset="UTF-8">app
<title>JS</title>post
<style>學習
#box{url
width:600px;code
height:200px;orm
padding:20px;htm
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>
須要代碼學習資料的同窗,能夠加羣434623999