ajax利用json发送/接收数据:

// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }

// 创建 XMLHttpRequest对象,以发送ajax请求
function createXMLHTTP() {
    var xmlHttp = false;
    var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
                         "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                         "Microsoft.XMLHTTP"];
    for (var i = 0; i < arrSignatures.length; i++) {
        try {
            xmlHttp = new ActiveXObject(arrSignatures[i]);
            return xmlHttp;
        }
        catch (oError) {
            xmlHttp = false; //ignore
        }
    }
    // throw new Error("MSXML is not installed on your system.");
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }
    return xmlHttp;
}

var xmlReq = createXMLHTTP();

// 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
function validatePwd(oTxt) {
    var url = "/AjaxOperations.aspx?action=jsonOp";
    // JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,所以可以轻松利用JSON并将其应用到服务器。
    var str = '{ "userName":"' + $("txtUserName").value + '", "userPwd": "' + $("txtPwd").value + '"}';
    var jsonStr = str.parseJSON().toJSONString();     //  you're sending it JSON
    xmlReq.open("post", url, true);
    xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlReq.onreadystatechange = callBack;
    xmlReq.send("sendStr=" + jsonStr); // 发送JSON(在服务器上解释JSON)
}

function callBack() {
    if (xmlReq.readyState == 4) {
        if (xmlReq.status == 200) {
            var jsonStr = xmlReq.responseText.parseJSON().toJSONString(); //转化为json数据
            alert(jsonStr);
        }
        else if (xmlReq.status == 404) {
            alert("Requested URL is not found.");
        } else if (xmlReq.status == 403) {
            alert("Access denied.");
        } else
            alert("status is " + xmlReq.status);
    }
}
多学多学,....

猜你喜欢

转载自714623591.iteye.com/blog/1656735
今日推荐