100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > xhr返回值_XMLHttpRequest发送POST GET请求以及接收返回值

xhr返回值_XMLHttpRequest发送POST GET请求以及接收返回值

时间:2020-08-24 11:09:08

相关推荐

xhr返回值_XMLHttpRequest发送POST GET请求以及接收返回值

/kf/03/193374.html

使用XMLHttpRequest对象分为4部完成:

1.创建XMLHttpRequest组建

2.设置回调函数

3.初始化XMLHttpRequest组建

4.发送请求

实例代码:

[javascript]

var userName;

var passWord;

var xmlHttpRequest;

//XmlHttpRequest对象

function createXmlHttpRequest(){

if(window.ActiveXObject){ //如果是IE浏览器

return new ActiveXObject("Microsoft.XMLHTTP");

}else if(window.XMLHttpRequest){ //非IE浏览器

return new XMLHttpRequest();

}

}

function onLogin(){

userName = document.f1.username.value;

passWord = document.f1.password.value;

var url = "LoginServlet?username="+userName+"&password="+passWord+"";

//1.创建XMLHttpRequest组建

xmlHttpRequest = createXmlHttpRequest();

//2.设置回调函数

xmlHttpRequest.onreadystatechange = zswFun;

//3.初始化XMLHttpRequest组建

xmlHttpRequest.open("POST",url,true);

//4.发送请求

xmlHttpRequest.send(null);

}

//回调函数

function zswFun(){

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

var b = xmlHttpRequest.responseText;

if(b == "true"){

alert("登录成功!");

}else{

alert("登录失败!");

}

}

}

================================================================================

[javascript]

var xmlhttp;

function verify1() {

var username = document.getElementById("username").value;

//确定浏览器

if(window.XMLHttpRequest) {

//针对FireFox、Mozillar、Opera、Safari、IE7、IE8

//创建XMLHttpRequest对象

xmlhttp = new XMLHttpRequest();

//修正某些浏览器的BUG

if(xmlhttp.overrideMimeType) {

xmlhttp.overrideMimeType("text/html");

}

}else if(window.ActiveXObject){

//针对IE5、IE5.5、IE6

//这两个为插件名称作为参数传递,为了创建ActiveXObject

var activeName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];

for(var i=0;i>activeName.length();i++) {

try{

//非别取出,如果创建成功则终止循环,如果失败则会抛出异常继续循环

xmlhttp = new ActiveXObject(activeName[i]);

break;

}catch(e){

}

}

}

//确定XMLHttpRequest是否创建成功

/*if(!xmlhttp) {

alert("XMLHttpRequest创建失败!");

return;

}else {

alert("XMLHttpRequest创建成功!"+xmlhttp);

}*/

//注册回调函数

xmlhttp.onreadystatechange=callback;

url = "classisservlet?name="+username;

//设置连接信息

//1.是http请求的方式

//2.是服务器的地址

//3.是采用同步还是异步,true为异步

//xmlhttp.open("GET",url,true);

//post请求与get请求的区别

//第一个参数设置成post第二个只写url地址,第三个不变

xmlhttp.open("POST","classisservlet",true);

//post请求要自己设置请求头

xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//发送数据,开始与服务器进行交互

//post发送请求

xmlhttp.send("name="+username);

}

function callback() {

//接收响应数据

//判断对象状态是否交互完成,如果为4则交互完成

if(xmlhttp.readyState == 4) {

//判断对象状态是否交互成功,如果成功则为200

if(xmlhttp.status == 200) {

//接收数据,得到服务器输出的纯文本数据

var response = xmlhttp.responseText;

//得到div的节点将数据显示在div上

var divresult = document.getElementById("result");

divresult.innerHTML = response;

}

}

}

[javascript]

[plain]

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。