如何将AJAX响应显示为警报

时间:2016-10-12 07:23:12

标签: javascript ajax

这是我的代码,我目前在元素的innerHTML中显示了AJAX请求的响应,但我希望alert代替响应结果。我怎么能这样做?

function checkforsampleAdded(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch(e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4) {
            var ajaxDisplay = document.getElementById('school_name');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }

    var status = document.getElementById('teststatus').value;
    var tstid = document.getElementById('tstid').value;

    ajaxRequest.open("GET", "<?php echo base_url();?>Test/CheckForSampleAdded/" + tstid, true);
    ajaxRequest.send(); 
}

1 个答案:

答案 0 :(得分:1)

除了检查readyState之外,我还建议您检查状态为200

这是更新后的代码

ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
            var ajaxDisplay = document.getElementById('school_name');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
            alert(ajaxRequest.responseText); // alert the data
        }
    }