Title rewritten to: Error: "SyntaxError: """ is not a legal JSON format"
P粉716228245
P粉716228245 2023-08-22 17:53:58
0
2
406

I have a question about the following code. The output of console.log is:

The URL I requested via a JavaScript Ajax request was "login.php":

getUsersLogin($username); if (!empty($user) && $user[0]['login'] == $username) { $json = json_encode(array("success" => 1)); echo $json; } else { $json = json_encode(array("success" => 0)); echo $json; } } ?>

My JavaScript Ajax request:

$(() => { $('.login-form').on('submit', function (e) { e.preventDefault(); $.ajax({ type: "POST", dataType: "json", timeout: 500, url: '/src/login.php', data: $(this).serialize(), success: (data) => { try { var jso = JSON.parse(data); console.log(jso); } catch (e) { console.log(e); return false; } }, error: (data) => { console.log(JSON.parse(data)); } }); }); });

Why is PHP's response of {"success":1} incorrect? what is the problem?

SyntaxError: "[object Object]" is not valid JSON


P粉716228245
P粉716228245

reply all (2)
P粉738248522

Try this to avoid this error:

myFunction(data: string) { try { JSON.parse(data); console.log(data); } catch (e) { console.log(e); } }
    P粉505450505

    If you writedataType: "json", then jQuery will automatically parse your response into JSON before entering the "success" function. This isdescribed in detailin jQuery's$.ajaxdocumentation.

    Therefore,datais already an object. You cannot pass an object toJSON.parse()- it expects a string.

    So, no need

    var jso = JSON.parse(data); console.log(jso);

    You can write directly

    console.log(data);
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!