【问题标题】:How to create a JSON rest webservice in php without using any library?如何在不使用任何库的情况下在 php 中创建 JSON REST Web 服务?
【发布时间】:2010-10-30 13:05:03
【问题描述】:

我想在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> 

【问题讨论】:

  • 为什么不使用 jQuery 或其他库?
  • 因为我想先学基础(json + xmlhttprequest)

标签: php javascript ajax web-services json


【解决方案1】:
  1. PHP 代码开始前有空格,所以header 调用会出错
  2. 您正在为 JSON 数据设置 text/html Content-Type,它应该是 application/json
  3. 您正在用字符串替换对表单中输入元素的引用,您可能希望将其设置为.value 属性。 (就此而言,为清楚起见,您可能应该以 document.forms.id_of_form.elements.dyn.value 访问它)(尽管首先使用 input 显示输出是一种相当可疑的做法)

【讨论】:

  • 我已经考虑了 1 和 2。我只想显示警报而不是 3,但它不起作用。
猜你喜欢
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2018-10-28
  • 2017-01-03
  • 2015-06-07
  • 1970-01-01
  • 2012-04-22
相关资源
最近更新 更多