function ajax2() { //原生写法,post请求,不可以带数据 //1.创建XMLHttpRequest对象 var xmlHttp; if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest();//火狐,谷歌浏览器等 }else{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器 } //2.使用open方法建立与服务器的链接 xmlHttp.open("POST","ajaxServlet",true);//true表示异步请求,false表示同步 xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlHttp.send("username=小明"); //3.在回调函数中对服务器响应的数据进行处理 xmlHttp.onreadystatechange=function() { //判断status响应状态码是否为200,readyState 就绪码是否是4 if(xmlHttp.status==200 && xmlHttp.readyState==4){ //获取服务器返回的内容,响应的结果 //获取服务器返回的内容 var responseText = xmlHttp.responseText; alert(responseText) }else{ alert("服务器异常...") } }
<body> <input type="button" value="发送请求" οnclick="ajax()"> 请输入:<input type="text"> </body>