原生ajax发送post请求

来源:互联网 发布:网络许可 英文 编辑:程序博客网 时间:2024/05/26 02:54

 1. 创建一个xmlhttpRequest对象
 2. 设置回调监听
 3. 打开一个连接
    接受两个参数:1. httpMethod   2. httpUrl
 4. 设置请求头(get没有该步骤)
    通知浏览器请求体的相关设置
 5. 发请求
    参数: 具体发送的值


readystate:

0 - (未初始化)还没有调用send()方法 
1 - (载入)已调用send()方法,正在发送请求 
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容 
3 - (交互)正在解析响应内容 
4 - (完成)响应内容解析完成,可以在客户端调用了 


/* 测试post类型的Ajax请求 1. 创建一个xmlhttpRequest对象 2. 设置回调监听 3. 打开一个连接    接受两个参数:1. httpMethod   2. httpUrl 4. 设置请求头    通知浏览器请求体的相关设置 5. 发请求    参数: 具体发送的值 */window.onload = function () {    document.getElementById('postBtn').onclick = function () {        // 1. 创建一个xmlhttpRequest对象        var xmlHttp = createXMLHttp();        // 2. 设置回调监听        xmlHttp.onreadystatechange = function () {            if(4 === xmlHttp.readyState && 200 === xmlHttp.status){                //局部刷新                document.getElementById('result').innerHTML = xmlHttp.responseText;            }        };        // 3. 打开一个连接        xmlHttp.open('POST', '/');        // 4. 设置请求头        xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");        // 5. 发送        xmlHttp.send('name=value&age=12'); //请求体body,用&分隔。引用:req.body.name    }};function createXMLHttp() {    var xmlhttp;    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari        xmlhttp = new XMLHttpRequest();    } else {// code for IE6, IE5        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");    }    return xmlhttp;}

原创粉丝点击