Ajax访问JSON(备忘)

(function() {  

    var createRequest = function() {  

        var request;  

        try { //support IE7+, Firefox, Chrome, Safari and Opera.  

            request = new XMLHttpRequest();  

        } catch(tryMS) {  

            try {  

                request = new ActiveXObject("Msxml2.XMLHTTP");  

            } catch(otherMS) {  

                try { // support IE6 and IE5  

                    request = new ActiveXObject("Microsoft.XMLHTTP");  

                } catch(failed) {  

                    request = null;  

                }  

            }  

        }  

        return request;  

    }  

      

    var checkText = function() {  

        var request = createRequest();  

        var obj = this;  

        if(request === null) {  

            alert("Unable to create request!");  

        } else {  

            var url = "json/test.json?id=" + Math.random();  

            request.onreadystatechange = function() {  

                if(request.readyState == 4 && request.status == 200) {  

                    var json = JSON.parse(request.responseText),  

                        text = obj.value;  

                    document.getElementById("prompt").innerHTML = json[text];  

                }  

            }  

            request.open("GET", url, true);  

            request.send(null);  

        }  

    }  

      

    document.getElementById("text").onkeyup = checkText;  

})();  

  

  

\\------------jquery  

  

  

$(function() {  

    $("#text").keyup(function() {  

        var $domText = $(this);  

        $.ajax( {  

            async: true,  

            cache: false,  

            type: "get",  

            url: "json/test.json",  

            dataType: "json",  

            success: function(data) {  

                $("#prompt").html(data[$domText.val()]);  

            }  

        });  

    });  

});  

  

你可能感兴趣的:(Ajax)