简体   繁体   English

语法错误:JSON.parse?

[英]SyntaxError: JSON.parse?

So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results) . So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results) . The application lets me pick a client and it pulls out that client's orders该应用程序让我选择一个客户并提取该客户的订单

JS file: JS文件:


function getOrders(clientId) {
    $.ajax(
            {
            type: 'POST',
            url: "AjaxRequests.php",
            data : {
                action: 'showOrders',
                clientId: clientId
            },
            dataType : 'json',
            success: function(results){
                alert(results);
            },
            error: function(request, status, error){
                console.log(clientId);
                console.log(request.responseText);
                console.log('error : ' + error);
                console.log('status' + status);
            },
            
            }
    )
};

AjaxRequests.php file AjaxRequests.php 文件

<?php 
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'showOrders') {
        $clientId = $_POST['clientId'];
        $gc = new GestionClients();
        $results = $gc->getCmdsByClient($clientId);
        echo json_encode($results);
    }
}

?>

and this is the results i get in the console after i pick a client (first client in this example with an ID = 1 in the DB) from the selection list:这是我从选择列表中选择一个客户端(本例中的第一个客户端,在数据库中 ID = 1)后在控制台中得到的结果:

1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror

I tried putting that JSON result on an online JSON parser and it looks just fine.我尝试将 JSON 结果放在在线 JSON 解析器上,它看起来很好。 Thank you for your time.感谢您的时间。

As I so often advise, this problem could have been avoided, or at least quickly identified, by breaking the problem down: you were trying to debug the JS, but that wasn't the part that was broken.正如我经常建议的那样,通过分解问题可以避免或至少快速识别这个问题:您试图调试 JS,但这不是被破坏的部分。

In this case, you have two key pieces:在这种情况下,您有两个关键部分:

  1. A PHP script that, when requested with the right parameters, outputs something.一个 PHP 脚本,当使用正确的参数请求时,输出一些东西。 You can open this in your browser, and see it for yourself.您可以在浏览器中打开它,然后自己查看。
  2. Some JS code which requests that PHP script, and parses its content as JSON.一些 JS 代码请求 PHP 脚本,并将其内容解析为 JSON。 You can test this with a PHP script that just echoes {"hello": "world"} , or even a text file uploaded to your server.您可以使用仅回显{"hello": "world"}的 PHP 脚本,甚至是上传到服务器的文本文件来对此进行测试。

Once you know that the JS code works if the JSON is valid, you can basically ignore #2, and look for problems in #1.一旦你知道如果 JSON 有效,JS 代码可以工作,你基本上可以忽略 #2,并在 #1 中查找问题。

If you open the PHP script you wrote in a browser, it will show:如果您在浏览器中打开您编写的 PHP 脚本,它将显示:

Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]

Now, we know that the JS is going to try to parse this as JSON, so we can do a quick test in our browser's console:现在,我们知道 JS 会尝试将其解析为 JSON,因此我们可以在浏览器的控制台中进行快速测试:

JSON.parse('Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');

We get a syntax error, Well: of course we do.我们得到一个语法错误,嗯:我们当然会。 that "Connection successfull!"那个“连接成功!” wasn't supposed to be part of the JSON.不应该是 JSON 的一部分。

So we dig into the PHP code, work out where that's coming from, and stop it happening.因此,我们深入研究 PHP 代码,找出它的来源,并阻止它发生。 Now we run the PHP again, and it looks like this:现在我们再次运行 PHP,它看起来像这样:

[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]

Now we can do our JS test again:现在我们可以再次进行 JS 测试:

JSON.parse('[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');

Now the error's gone away, and it gives us an array.现在错误消失了,它给了我们一个数组。 While we're here, we can look at the structure of the array in the console and make sure it looks right.当我们在这里时,我们可以在控制台中查看数组的结构并确保它看起来正确。

Only now do we go back and run the original AJAX call, and see if it's all working.直到现在我们才返回 go 并运行原始的 AJAX 调用,看看它是否全部工作。 If it's not, we look for other steps we can break out, and repeat the process.如果不是,我们寻找可以突破的其他步骤,并重复该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的SyntaxError意外的数字JSON.parse - Uncaught SyntaxError Unexpected Number JSON.parse 语法错误:JSON.parse:意外字符 - SyntaxError: JSON.parse: unexpected character jQuery ajax-SyntaxError:具有优良json的JSON.parse - jQuery ajax - SyntaxError: JSON.parse with fine json JSON.parse 单个变量 - Uncaught SyntaxError: Unexpected token &lt; in JSON - JSON.parse single variable - Uncaught SyntaxError: Unexpected token < in JSON SyntaxError: JSON.parse: 在 json 输出中使用 URL 时预期 - SyntaxError: JSON.parse: expected when using a URL in json output SyntaxError: JSON.parse: JSON 第 1 行第 2 列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON 语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 未捕获到的SyntaxError:JSON中的意外令牌&lt;在JSON.parse位置0处( <anonymous> ) - Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) SyntaxError:JSON中的意外令牌&lt;位于JSON.parse(位置0) <anonymous> )-AngularJS - SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) - AngularJS SyntaxError: JSON.parse: AJAX 调用中出现意外字符错误 - SyntaxError: JSON.parse: unexpected character error in AJAX call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM