将XMLHttpRequest.responseText存储为变量:( [英] store XMLHttpRequest.responseText as variable :(

查看:260
本文介绍了将XMLHttpRequest.responseText存储为变量:(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<script language="javascript" type="text/javascript">

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 result = ajaxRequest.responseText;      
    }
}
ajaxRequest.open("GET", "vartest.php", true);
document.getElementById('span').innerHTML = result;
ajaxRequest.send(null);

}

推荐答案

这是因为Ajax是异步的,并且在执行此操作时尚未设置result(无论如何,var使其在该函数中是局部的) ,则必须将其删除).

This is because Ajax is asynchronous, and result isn't set yet when you do this (plus the var makes it local to the function anyway, you'd have to remove that).

最好的办法是将innerHTML行移到readystatechange回调中.

The best thing to do would be to move the innerHTML line into the readystatechange callback.

ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
   document.getElementById('span').innerHTML = ajaxRequest.responseText;;      
}

这篇关于将XMLHttpRequest.responseText存储为变量:(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆