simple Ajax (local): responseText is empty

simple Ajax (local): responseText is empty

本文关键字:responseText is empty Ajax local simple      更新时间:2023-09-26

我尝试使用教程中的示例,但响应文本只是空的。如果我尝试'alert'我得到OK,但与responseText,弹出窗口只是空的,在它什么都没有。为什么会这样?

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);  
}  

函数'start'被onsubmit调用:

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

和PHP页面:

<?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";  
}  
?>   

我以为按照教程去做是可以的,但事实并非如此你能告诉我有什么不对劲吗?

嘿我能建议你做点什么让你的生活更轻松吗?

试试jQuery的ajax库——这么简单

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

在你的情况下…

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

在许多浏览器中,Javascript安全设置不允许通过file:协议加载的页面中包含的脚本进行Ajax调用。如果可能的话,尝试从可以利用http:协议的位置加载页面。苹果的开发者网站http://developer.apple.com/internet/webcontent/xmlhttpreq.html有一些其他的考虑因素可能会导致你所看到的结果。(向下滚动到"安全问题"部分)