Ajax发送post请求

来源:互联网 发布:网络电视机软件下载 编辑:程序博客网 时间:2024/05/19 05:05

Ajax发送post请求

发送POST请求的注意点:

(1)请求方法为post(2)把要提交的参数放在send方法中处理(3)必须设置请求头信息    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

封装好的代码示例

// 数据处理方法function json2str(data) {    var arr = [];    for(var key in data){        arr.push(key+"="+data[key]);    }    // 不能直接将中文提交给服务器, 中文需要编码之后再提交    return encodeURI(arr.join("&"));}// 发送请求方法// function myAjax(type, url, data,timeout,success, error) {function myAjax(option) {    // -1.默认值处理    option.type = option.type || "get";    option.timeout = option.timeout || 15;    // 0.对参数进行处理    var res = json2str(option.data);    // 1.创建异步对象    if(window.XMLHttpRequest){        var xhr = new XMLHttpRequest();    }else{        var xhr = new ActiveXObject("Microsoft.XMLHTTP");    }    if(option.type == "get"){        // 2.设置URL        xhr.open(option.type, option.url+"?"+res, true);        // 3.发送请求        xhr.send();    }else{        // 2.设置URL        xhr.open(option.type, option.url, true);        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");        // 3.发送请求        xhr.send(res);    }    // 4.监听状态    xhr.onreadystatechange = function () {        // 5.处理返回结果        if(xhr.readyState == 4){            // 清空定时器            clearTimeout(timer);            if(xhr.status >= 200 &&                xhr.status < 300 ||                xhr.status == 304){                option.success(xhr);            }else{                option.error(xhr.status);            }        }    }    // 6.对超时时间处理    if(!option.timeout){        return;    }    var timer = setTimeout(function () {        alert("超时了");        // 中断请求        xhr.abort();    }, option.timeout);}


原创粉丝点击