简体   繁体   中英

SyntaxError: Unexpected token < in JSON at position 0” error in AJAX

I'm sending data through ajax request and after processing the data an array is returned, which is encoded to json format.

$response = array(
            'data' => $leaveData,
            'message' => 'Event added successfully',
            'status' => 'success'
        );
echo json_encode($response);
exit;

where $leaveData is an associative array:

   Array
(
    [id] => 131
    [user_id] => 134
    [leave_type_id] => 2
    [issued_date] => 2017-10-17
    [leave_from] => 2017-10-25
    [leave_to] => 2017-10-26
    [leave_description] => test
    [leave_status] => 1
)

Here's my ajax request:

$.ajax({
url:"leave/request",
data:{
  id:eventID,
  user_id:empID,
  leave_type:leaveType,
},
  type:"POST",
  cache:false,
  success: function (data, resp){
    var json = data, 
    obj = JSON && JSON.parse(json) || $.parseJSON(json);
  }
});

Also, I think JSON && JSON.parse(json) || $.parseJSON(json) JSON && JSON.parse(json) || $.parseJSON(json) are used for the same purpose?

I have no idea what is going wrong.

I encountered the same problem just a few while ago and the problem lies within the data I was trying to pull into success callback, I just removed the static variables and such that I was trying to get into the json and kept the its values strictly coming only from the query results. Maybe it's the same for you.

You could use the ajax dataType property to interprate JSON directly after ajax response like :

$.ajax({
    url:"leave/request",
    dataType: "json",
    data:{
        id:eventID,
        user_id:empID,
        leave_type:leaveType,
    },
    type:"POST",
    cache:false,
    success: function (data){
        console.log(data);
    }
});

Add an "error" callback to your ajax function, and then print the content:

  error: function(data) {
      console.log("AJAX ERROR:", data);
  }

This will show you what ajax is trying to parse as 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