为什么我不能用ajax显示我的数据?

时间:2012-09-07 19:58:07

标签: javascript jquery ajax

这是我的代码:

  var xml=new String("");     
 //function to send data every 5 seconds
        window.setInterval(function() { 
        //code to obtain xml file
            alert(xml);// when I try alert my variable xml contain data
            ajax_post(xml);
            }
        }, 5000); 


  //the function ajax_post


   function ajax_post(xml){
   // Create our XMLHttpRequest object
   var hr = new XMLHttpRequest();
   // Create some variables we need to send to our PHP file
    var url = "my_file.php";
    var vars = "xml="+xml;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}

问题是,当我尝试在div中显示我的数据时,我得到一个空输出,好像他让变量初始化为空,但有警报我可以显示我的数据。 为什么?

谢谢。

1 个答案:

答案 0 :(得分:2)

我相信你有一个额外的}它不应该是:

window.setInterval(function() { 
        //code to obtain xml file
            alert(xml);// when I try alert my variable xml contain data
            ajax_post(xml);
            }
        , 5000);