开发者

simple Ajax (local): responseText is empty

I've tried to use an example from a tutorial, but the response text is just empty. If I try with 'alert' I get OK, but with the responseText, the popup is just empty, nothing in it. Why is this?

function start(){  
var xhr = getXMLHttpRequest();  
var sVar1 = encodeURIComponent("firstContent");  
var sVar2 = encodeURIComponent("SecondContent");  
xhr.onreadystatechange = function() {  
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {  
        //alert("OK");  
                alert(xhr.responseText);  
    }  
}; 



xhr.open("GET", "handlingData.php?variable1=" + sVar1 + "&variable2= " + sVar2, true);  
xhr.send(null);  
}  

The function 'start' is called by the onsubmit:

form id="form_userlogin" onsubmit="start()"  

And the PHP page:

<?php
header("Content-Type: text/plain");  
$variable1 = (isset($_GET["variable1"])) ? $_GET["variable1"] : NULL;  
$variable2 = (isset($_GET["variable2"])) ? $_GET["variable2"] : NULL;  
if ($variable1 && $variable2) {  
    echo "OK";  
} else {  
    echo "FAIL";  
}  
?>   
开发者_运维知识库

I thought it would be ok to follow the tutorial, but it's not ;p Can you please tell me if you see something wrong?


Hey man -- can I suggest doing something to make your life a whole lot easier?

Try jQuery's ajax library -- so simple

$.GET( url, {var1: val1, var2: val2}, function(data){ // do something with the data given back });

in your case...

$.GET(
   'http://yoursite/ajaxfunction',
   {get_var1: value1, get_var2: value2},
   function (data) {
      alert(data);
   });


In many browsers, the Javascript security settings won't allow scripts contained in a page loaded via the file: protocol to make Ajax calls. If possible, try loading the page from a location where you can utilize the http: protocol. Apple's developer site, at http://developer.apple.com/internet/webcontent/xmlhttpreq.html, has some other considerations that may cause the results you are seeing. (Scroll down to the "Security Issues" section.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜