eightHundreds
4/29/2017 - 1:45 AM

ajax.js

ajax封装

function MyAjax(method, url, callback, parameter) {
    /// <summary>Ajax封装,实现对服务服务,并用回调函数处理ResponseText</summary>
    /// <param name="method" type="String">请求方法</param>
    /// <param name="url" type="String">请求地址</param>
    /// <param name="callback" type="function">回调函数</param>
    /// <param name="parameter" type="??">当请求方法为Post的时候用到</param>
    var xhr;
    if (XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    
    xhr.open(method, url, true);
    if (method.toString().toUpperCase() == "POST") {
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(parameter)//JSON.stringify
    } else {
        xhr.send();
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200&&callback!=undefind) {
            callback(xhr.responseText); //用回调函数处理返回字符串
        }
    }
}