Title rewritten to: Error: "SyntaxError: """ is not a legal JSON format"
P粉716228245
2023-08-22 17:53:58
<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>
Try this to avoid this error:
If you write
dataType: "json"
, then jQuery will automatically parse your response into JSON before entering the "success" function. This isdescribed in detail
in jQuery's $.ajax documentation.Therefore,
data
is already an object. You cannot pass an object toJSON.parse()
- it expects a string.So, no need
You can write directly