JS中的fetch没有从php中的json_encode接收适当的JSON格式

时间:2017-11-25 03:58:36

标签: javascript php json

我在JS中有一个从php页面获取数据的函数。

JS代码:

fetch("print.php)
    .then(function (r) {
        return r.json()
    })
    .then(function (values) {
        ......
        ......
    })
}

PHP print.php代码:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $num = $_GET['num'];
    $datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);
    $result;
    foreach ($datas as $index => $data) {
        if ($data[0] == $num) {
            $result = $data;
        }
    }

    echo json_encode($result);
}

当我运行我的代码时,我收到以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

任何人都可以帮我调试这个。 我试过回声json_encode([$ result]);但它没有用。 过去3个小时我一直试图修复它,但我没有希望。我不知道去哪个方向。

更新: screenshot of the header

1 个答案:

答案 0 :(得分:-1)

首先,如果在此处粘贴代码时不仅仅是拼写错误,那么PHP文件末尾会有额外的结束括号。

关于代码,以及不清楚文件myFile.txt中的内容,让我向您展示一个如何工作的示例。 您可以在本地计算机上按照这些步骤复制该示例,并看到它在您的最终工作。

让我们说我有这个简单的PHP文件名fetch.php

<?php 
if($_SERVER['REQUEST_METHOD'] == 'GET'){
    echo json_encode(['Message'=>'you successfully received the response.']);
}
?>

创建HTML页面sample.html并在body标记内添加以下内容。

<ul>
    <li class="print"></li>
</ul>

现在在HTML标记之前的</body>页面底部添加以下脚本。

<script type="text/javascript">
  $(document).ready(function(){
    var resultContainer = document.querySelector('ul li.print');

    fetch('fetch.php')
    .then(function (response) {
        return response.json();
    })
    .then(function (response) {
        resultDiv.innerHTML = response.success;
    }).catch(function(err){
        resultDiv.innerHTML='There was an error reading the JSON response see here '+err;
    });
   });
</script>

由于我们提取的PHP文件正在返回json,我们会在response.json()上返回response,以便为其提供正确的MIME类型,以便它将被正确处理,then将其显示在<li>元素中。此外,我正在使用。fail显示错误消息,如果Promise被拒绝

这很简单,一旦Promise结算,它应该会在li里面显示你成功收到回复。的文字。如果是,则表示您需要首先对PHP文件进行问题排查,以查看myFile.txt中的内容以及当到达最后一行echo json_encode($result);时打印的内容。

此外,您的PHP文件表明您正在将查询参数num发送到PHP文件,而您的脚本不包含任何名为{{1}的查询字符串参数}。

其次num在行$result;之后做什么,你的大多数代码没有任何意义,你应该完成你的任务并提供其他人可以理解和帮助你的实际敏感代码。

希望能帮到你