简体   繁体   中英

PHP JSON header causes error on JSON.parse (using jQuery)

I am getting some JSON data in JavaScript from a PHP file.
To use the data, I am using JSON.parse(json_response) which works except if I use a JSON header in my PHP:

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

When used, I get the following message in console:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

At the moment I just choose between using the PHP header() or the JS JSON.parse() and found this useful question .
It looks like setting a JSON header "automatically parses" the JSON for my JS script.

  • Is it a normal behaviour ? What may cause this ?
  • What should I do ? Randomly choosing between header() and JSON.parse() probably isn't a good idea.

Actual code:
index.chart.php :

<?php

header('Content-Type: application/json');
// [...] <- config lines, no output


// Dummy data for Chart.js
$data = [
    'labels'   => ['test', 'a', 'z', 'e', 'r', 't'],
    'datasets' => [
        [
            'label'           => 'First',
            'backgroundColor' => 'rgb(63, 123, 249)',
            'borderColor'     => 'rgb(31, 117, 219)',
            'data'            => [
                20, 10, 30, 45, 51.2, 5
            ],
            'fill' => false
        ]
    ]
];

echo json_encode($data);

?>

index.chart.js :

window.addEventListener('DOMContentLoaded', function () {

    // jQuery Ajax
    $.get('assets/inc/index.chart.php').done(function (json) {

        var response = JSON.parse(json);
        console.log(response);

    }).fail(function (error) {
        window.console.log(error);
    });

});

If you don't specify a dataType then jQuery will determine what type of data is received from a URL using the Content-Type header and run it through an appropriate parser.

json is not a string of JSON, it is a JavaScript object that you got from parsing the JSON.

The input to JSON.parse needs to be a string of JSON.

Change:

 function (json) { var response = JSON.parse(json); 

To:

function (response) {

Is it a normal behaviour ? What may cause this ?

Yes, this is normal behavior, jQuery.ajax has converters that are used to automatically run certain functions on the returned data. For requests that return JSON headers, that is jQuery.parseJSON , meaning, that the data that gets passed to the callback function is already parsed JSON.

What should I do ? Randomly choosing between header() and JSON.parse() probably isn't a good idea.

You are right, that would only make your code harder to follow. Choose one and keep it throughout the project. If you are currently using other services for example, that don't have the right headers set up for JSON, I would suggest always using JSON.parse and not using the header function here.

I may be wrong about this but:

The header() function must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

Try remove the space between the php opening tag and the header function:

<?php
header('Content-Type: application/json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM