我想在test.php中创建一个hello world json rest webservice:
<?php header("Content-type: application/json; charset=utf-8");
$test[] = "hello";
$test[] = "world";
$json = json_encode($test);
echo $json;
?>
但是当我用ajax测试它时为什么没有返回?
<html>
<head>
<script>
function test()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
alert(xhr.responseText);
else
alert("Error code " + xhr.status);
}
};
xhr.open(GET, "test.php", true);
xhr.send(null);
}
</script>
</head>
<body>
<script>
test();
</script>
</body>
</html>
答案 0 :(得分:1)
header
调用将会出错text/html
Content-Type,它应为application/json
.value
属性。 (就此而言,为了清楚起见,您可能应该以{{1}}的形式访问它)(尽管使用document.forms.id_of_form.elements.dyn.value
来显示输出是一个相当可疑的做法,但是)