JavaScript使用XMLHttpRequest 發送GET/Post 請求

<!DOCTYPE HTML>
<html>
<head>
<title>Demo</title>
<script type="text/javascript">
	
	 var xmlHttp;  
	
	//XmlHttpRequest对象
	function createXMLHttpRequest() {  
    var xmlHttp;  
    if (window.XMLHttpRequest) {  //非IE浏览器  
        xmlHttp = new XMLHttpRequest();  
        if (xmlHttp.overrideMimeType)  
            xmlHttp.overrideMimeType('text/xml');  
    } else if (window.ActiveXObject) {  //如果是IE浏览器 
        try {  
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  
        } catch (e) {  
            try {  
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
            } catch (e) {  
            }  
        }  
    }  
    return xmlHttp;  
   }  
   
   	function getStatusBack(){  
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200){  
            var b = xmlHttp.responseText;  
            alert(b);
            console.log(b);
        
        }  
    }  
   function testGet(){
   	
   	 xmlHttp = createXMLHttpRequest();  
     var url = "http://xxx/xxx/xxx"  
     xmlHttp.open("GET", url, true);// 异步处理返回   
     xmlHttp.onreadystatechange = getStatusBack;   //设置回调函数 
     xmlHttp.setRequestHeader("Content-Type",  "application/x-www-form-urlencoded;");  
     xmlHttp.send();  //发送请求
   	}
   	function testPost(){
   		var parameter = "tidList=1"
   		 var url = "http://xxx/xxx/xxx";  
   	   xmlHttp = createXMLHttpRequest();
   	   xmlHttp.open("POST", url, true);  
  		 xmlHttp.onreadystatechange = getStatusBack; //设置回调函数  
			 xmlHttp.setRequestHeader("Content-Type",  
			 "application/x-www-form-urlencoded;");  
			 xmlHttp.send(); //发送请求
   	}
 	

</script>
</head>
		
<body>

		<button  onclick="testGet()">Test Get</button>
		<button  onclick="testPost()">Test Post</button>
</body>
</html>

  

你可能感兴趣的:(JavaScript使用XMLHttpRequest 發送GET/Post 請求)