您好,我正在尝试编写脚本以从 PHP 站点取回 XML 文本。但是,它不返回任何数据。这就是我正在做的事情。
<head>
<script type="text/javascript">
function getImei()
{
var imei = document.getElementById("imeiInput").value;
if (imei=="")
{
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtResult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.phonesite.com/xml/api/phone.php?IMEI=" + imei,true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="textbox" id="imeiInput"/>
<input type="button" onClick="getImei()" id="btnSubmit" text="Submit"/>
<p id="txtResult"></p>
</body>
</html>
当我这样做时,xmlhttp.readystate 停在 1。当我将“xmlhttp.onreadystatechange = function()”放在 xmlhttp.send() 下方时,它表示 FireBug 中的就绪状态为 4,但它完全跳转在不进入函数内部的情况下结束函数。
此外,我确实尝试在我的浏览器中直接输入带有查询字符串的 url,它返回了文本。查看 GET 请求,当 Javascript 发出和输入时它们是相同的。
Date Fri, 14 Oct 2011 01:34:05 GMT
Server Apache
Content-Encoding gzip
Vary Accept-Encoding
Content-Length 87
Keep-Alive timeout=15, max=100
Connection Keep-Alive
Content-Type text/xml
Request Headersview source
Host www.phonesite.com
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
我在 xml 文本的 Firebug 中收到此错误。
XML Parsing Error: no element found Location: moz-nullprincipal:{baefeeae-cd08-9641-a08f-6b3c3396e8a7} Line Number 1, Column 1:
最佳答案
当您请求从服务器返回的响应是 XML 而不仅仅是文本时,您可以使用 responseXML 读取该响应
instead of "responseText"; you need for xml "responseXML"
这至少会返回文本并让您继续前进
function getImei()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var imei = document.getElementById("imeiInput").value;
if (imei=="")
{
return;
}
if(xmlhttp) {
xmlhttp.open("GET","http://www.phonesite.com/xml/api/phone.php?IMEI=?" + imei, true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtResult").innerHTML=xmlhttp.responseText; // if the returned content type is is "text/xml" innerhtml will strip out the tags
}
}
xmlhttp.send(null);
}
}
关于php - Ajax PHP 未向我提供任何响应文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7762665/