[英]How to create a JSON rest webservice in php without using any library?
I want to create a hello world json rest webservice in test.php: 我想在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;
?>
But nothing is returned when I test it with ajax below why ? 但是当我用下面的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>
header
call will error header
调用将出错 text/html
Content-Type for JSON data, it should be application/json
text/html
Content-Type,它应该是application/json
.value
property instead. .value
属性。 (For that matter, you should probably be accessing it as document.forms.id_of_form.elements.dyn.value
for clarity) (Using an input
to display output is a rather dubious practice in the first place though) document.forms.id_of_form.elements.dyn.value
形式访问它)(虽然使用input
显示输出是一种相当可疑的做法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.