简体   繁体   中英

Javascript json parsing of php response

I'm working on a project and use ajax to update some informations in forms.

Here is my ajax function :

function update_ad() {
    var project_name = document.getElementById("mol_project").value;
    if (project_name !== '') {
        $.ajax({
            type: 'POST',
            url: "controllers/get_project.php",
            data: {project_name: project_name},
            dataType: 'text',
            success: function (data) {
                var result = JSON.parse(data);

            }
        });
    }
}

On my development environement everything works fine. The function get the json text from php server and parse it so I can use data after that.

But on my production environement, I receive a parsing error :

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

Here is the received Json :

{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}

Jquery, apache and php version are the same on both environements. I guess it's a server configuration issue but I can't figure out where it is.

Okay, in your JSON, there's a UTF-8 BOM in the front. Can you find the difference between:

{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}

And:

{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}

Where the latter is a valid JSON. Check it out with JSONLint . You need to make sure that the output you are receiving is free of UTF-8 BOM.

When I tried using the encodeURI() function on the JSON, it gave me this output:

encodeURI(' {"pr'); // "%20%EF%BB%BF%7B%22pr" - Wrong one!
encodeURI(' {"pr'); // "%20%7B%22pr"          - Correct one!

We can make use of encodeURI to detect the anamolies and fix it in the client side. I am working on a solution.

The unicode signature, if you see, is EF BB BF , which is explained in this article . We can make use of this signature and try to correct it.

If you have the access to the PHP source, try setting the right headers :

header("Content-type: application/json; charset=utf-8");

replace dataType: 'text' to dataType: json,

Look at the spec for JSON (easily understood version here: http://json.org/ ). There is nowhere that says that parenthesis are valid. ({"foo": true}), for example will never parse. It may be evaled as it is valid javascript, but javascript is not 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