【发布时间】:2009-11-21 04:48:45
【问题描述】:
我的 html 页面向 PHP 发送一个 ajax 请求 (POST),PHP 回显一个 json 对象。
代码已经过测试,在我的开发视图中运行良好。
但是,上传到 VPS 托管服务器后,返回的 json 字符串为空(我在响应函数中使用 alert() 显示 responseText,发现它是空的)。
对这个问题有任何想法吗?
我是新来的。我还没有弄清楚如何添加评论。 (请告诉我。)
我更改了 PHP 代码以返回一个字符串,它起作用了。所以问题出在json编码之后。
新的test.php(工作)。
if(!isset($_POST['A'])||!isset($_POST['B']))
{
echo "Failed";
}
else
{
echo "OK";
}
HTML:
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
var NORMAL_STATE = 4;
function ajax_create_http()
{
var xmlHttp = 0;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return 0;
}
}
}
return xmlHttp;
}
var http_req_inst = ajax_create_http();
function sendHttpRequest(params)
{
if( !http_req_inst ) return;
http_req_inst.open('POST', 'test.php', true);
http_req_inst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_req_inst.onreadystatechange = handleHttpResponse;
http_req_inst.send(params);
alert("Request sent");
}
function handleHttpResponse()
{
if( !http_req_inst ) return;
if (http_req_inst.readyState == NORMAL_STATE)
{
alert(http_req_inst.responseText);
}
}
</script>
</head>
<body>
<div>
<input type="button" value="click" onclick="sendHttpRequest('A=a&B=b')"/>
</div>
</body>
</html>
PHP:
<?php
if(!isset($_POST['A'])||!isset($_POST['B']))
{
$rc = 1;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing failed.');
echo json_encode($arr);
}
else
{
$rc = 0;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing passed.');
echo json_encode($arr);
}
?>
当我测试时,responseText 是空的。
【问题讨论】:
-
尝试打印功能,但一些代码会有所帮助。
-
我建议您使用 Firebug 来调试您的回调函数并检查 Ajax 请求的详细信息...
-
帮自己一个忙,用 FirePHP firephp.org 调试 AJAX