简体   繁体   中英

Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>)

i know that there's so many questions about this but sorry im really confuse about this error...

i created a login page and i used ajax for the POST Request..what happens is when i used this

$.ajax({
 url:'../ajax/checklogin.php',
 type:'POST',
 dataType:'JSON',
 data:$('form').serialize(),   
  success: function(result){
  $.post("../www/login.php",{ users_id: JSON.parse(result.users_id)}).done(window.location.href='../www/index.php');
  }
});

the $.post is working but when i tried to add another field to parse i got this error.. the error is on users_active.. for some reason i dont have any idea why i got the error

$.post("../www/login.php",{ users_id: JSON.parse(result.users_id),users_active: JSON.parse(result.users_active)}).done(window.location.href='../www/index.php');

the other field are fine but the only field that gives me error is the users_active.. i even check the json array that is being returned they are valid json...

JSON.parse() takes a string and turns it into a JavScript object.

You are lucky, that JSON.parse("12345") can be converted to new Number("12345") , which is indeed an integer.

result.users_active is already a JavaScript object (or array) or maybe a String, which not represents a JSON object, so the parse will result in a syntax error as stated in https://www.w3schools.com/js/js_json_parse.asp .

I assume, you need JSON.stringify() , but to assure that, you should post some code or your result object. https://www.w3schools.com/js/js_json_stringify.asp

Edit: Now that I have seen the object, "active" is a simple string and you can't strip the quotes. So just use users_active: result.users_active .

JSON.parse doesn't remove quotes ("), but converts your data into objects, booleans or strings - if they were valid json before (not just the values of the properties, which you have passed). See here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

If you want to assure that you pass integers or strings (or whatever you need) to your ajax post, just use the adequate javascript functions, like parseInt() or String().

See here an example with your data:

var result = {
  "id":"26",
  "users_id":
  "201710001",
  "users_username":"123",
  "users_active":"active"
  };

$.post("../www/login.php", { 
    users_id: parseInt(result.users_id),
  users_active: String(result.users_active) 
  }).done(window.location.href='../www/index.php');

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