在php中设置响应标头

时间:2019-08-02 16:28:49

标签: javascript php

如何在响应标头中从text / html将内容类型设置为application / json,我已经将请求标头内容类型设置为application / json但在text / html中显示了响应标头内容类型

这是我的代码

      function check(c2) {
          document.title = 'Checking';
                    var xmlhttp;
                    xmlhttp=new XMLHttpRequest();
                    xmlhttp.onreadystatechange = function()
                    {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200)
                        {
                            var xdata = xmlhttp.responseText;   
                        if (xdata.match("GOOD")) {
                          $("#GOOD").append(xdata);
                          document.getElementById("goodcnt").innerHTML = (eval(document.getElementById("goodcnt").innerHTML) + 1);
                          $("#listcnt").html(parseInt($("#listcnt").html()) - 1),
                          line('#cs');
                          Check();

                      } else if (xdata.match("BAD")) {
                         $("#BAD").append(xdata);
                         document.getElementById("badcnt").innerHTML = (eval(document.getElementById("badcnt").innerHTML) + 1);
                         $("#listcnt").html(parseInt($("#listcnt").html()) - 1),
                         line('#cs');
                         Check();
                      }
 }
                      }
                    xmlhttp.open("POST","api?list=" + c2 ,true);
                    xmlhttp.setRequestHeader("Content-Type","application/json");
                    xmlhttp.send();
      }

我也试图在api中添加此代码

header("Content-Type: application/json");

1 个答案:

答案 0 :(得分:1)

使用此行时:

xmlhttp.setRequestHeader("Content-Type","application/json");

您是在向服务器说发送的内容包含JSON。然后,当服务器响应时,它需要知道客户端支持JSON作为回复。

因此,您需要在下面添加以下行:

xmlhttp.setRequestHeader("Accept","application/json");

更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept

相关问题