JavaScript使用XMLHttpRequest 發送GET/Post 請求
Posted on 2016-10-12 14:06 work hard work smart 阅读(466) 评论(0) 编辑 收藏 举报<!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>
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!