Title rewritten to: Error: "SyntaxError: """ is not a legal JSON format"
P粉716228245
P粉716228245 2023-08-22 17:53:58
0
2
460
<p>I have a question about the following code. The output of <em>console.log</em> is: </p> <p>The URL I requested via a JavaScript Ajax request was "login.php": </p> <pre class="brush:php;toolbar:false;"><?php include('init.php'); use LoginLoginService; #include(__DIR__.'/Login/LoginService.php'); global $pdo; session_start(); $username = $_POST['username']; $pass = $_POST['password']; if (!empty($username)) { $test = new LoginService(); $user = $test->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; } } ?></pre> <p>My JavaScript Ajax request:</p> <pre class="brush:php;toolbar:false;">$(() => { $('.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)); } }); }); });</pre> <p>Why is PHP's response of <code>{"success":1}</code> incorrect? what is the problem? </p> <blockquote> <p>SyntaxError: "[object Object]" is not valid JSON</p> </blockquote><p><br /></p>
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 write dataType: "json", then jQuery will automatically parse your response into JSON before entering the "success" function. This is described in detail in jQuery's $.ajax documentation.

Therefore, data is already an object. You cannot pass an object to JSON.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!