0

这是我的代码:

  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 中显示我的数据时,我得到一个空输出,就好像他让变量初始化为空一样,但有了警报我可以显示我的数据。为什么 ?

谢谢你。

4

1 回答 1

2

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

window.setInterval(function() { 
        //code to obtain xml file
            alert(xml);// when I try alert my variable xml contain data
            ajax_post(xml);
            }
        , 5000); 
于 2012-09-07T20:00:32.060 回答