【问题标题】:Javascript "JSON.parse: unexpected character at line 2 column 1 of the JSON data" [closed]Javascript“JSON.parse:JSON数据第2行第1列的意外字符”[关闭]
【发布时间】:2021-10-12 14:56:30
【问题描述】:

我的 JSON 字符串如下所示

{"Peter":"35","Ben":"37","Joe":"43"} 

PHP 代码

class Products{
    public function example(){
        $results = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
        echo json_encode($results);
    }
}

Javascript 代码

const xhttp = new XMLHttpRequest();
xhttp.onload = function()
{
    const obj = this.responseText;
    const obj1 = JSON.parse(obj);
    alert(obj1);

}
xhttp.open("POST", "/products/example");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

当我在 javascript 中解析问题时,我得到了错误。

【问题讨论】:

  • 无法复制。
  • json 有效。你如何将 tis json 发送到解析器?您是否遇到带有转义字符“\”(缺失或过多)的问题?可以把代码放在这里吗?
  • 我在 php 中使用 $data=json_encode($result); print_r($data); 对其进行编码,并将其作为 ajax 响应发送到 javascript。使用const obj = JSON.parse(this.responseText); 在javascript中解析它“\”转义字符没有问题
  • 请编辑您的问题以包含您的 PHP 和 JavaScript 代码的 minimal reproducible example
  • 您尝试过什么解决问题的方法?你被困在哪里了?您是否检查过响应是否正确发送?

标签: javascript php json parsing codeigniter-4


【解决方案1】:

从 PHP 发送 JSON 时,您需要设置“Content-Type”标头,并且不能使用 print_r

<?php
$data=json_encode($result);
header('Content-Type: application/json');
echo $data;

尝试在浏览器的开发人员工具中查看 PHP 脚本的响应,以确保获得正确的 HTTP Content-Type 标头。

【讨论】:

  • 谢谢。这有帮助。我犯了一个错误,没有根据我使用的框架(即 Codeigniter 4)查看发送 HTTP 响应的正确方法。我设置了 Content-Type 并使用 Codeigniter 的响应对象发送了响应,它可以工作。这是代码$this-&gt;response-&gt;setContentType('application/json'); return $this-&gt;response-&gt;setJSON($results);
  • 我犯的另一个错误是没有提到我正在使用 Codeigniter 4。
猜你喜欢
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2020-01-11
  • 1970-01-01
  • 2017-05-18
  • 2020-04-17
  • 2020-09-15
相关资源
最近更新 更多