日期:2014-05-16  浏览次数:20691 次

ajax 简单封装
/** 调用远程服务器程序
*@_url    服务器url
*@_target 本地用于容纳返回结果的 html 元素,可以为空
*@async   true-异步调用 false-同步调用
*@params  附加调用参数
*@callback 服务器端成功返回后的回调函数
*返回值:如果同步调用,则返回服务器的返回结果值,否则直接返回 false
*/
function callToServer(_url, _target, async, params, callback) {
try {
    if (async==null||async==true) async=true;
        var ret;    
        var xmlHttp = createXMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {  // 4-READY_STATE_COMPLETE
                ret = xmlHttp.responseText;
                if (_target) {
                    var selObj = getElement(_target);
                    if (selObj) {
                        if (selObj.tagName && "input,textarea,select".indexOf(selObj.tagName.toLowerCase())>=0)
                            selObj.value=ret;
                        else {
                            try {
                                selObj.innerHTML=ret;
                            } catch (e1) {}
                        }
                    }
                }
               
                // 回调函数
                if (callback)
                    callback.call(this, ret);
            }           
        };
       
        xmlHttp.open("POST", _url, async); // true-异步 false-同步
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        xmlHttp.setRequestHeader("req-type", "ajax");      
        if (params && (typeof