简体   繁体   English

SyntaxError: Unexpected token < in JSON at position 0" 错误在 AJAX

[英]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.我通过ajax请求发送数据,处理完数据后返回一个数组,该数组被编码为json格式。

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

where $leaveData is an associative array:其中$leaveData是一个关联数组:

   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请求:

$.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) JSON && JSON.parse(json) || $.parseJSON(json) are used for the same purpose? JSON && JSON.parse(json) || $.parseJSON(json)用于相同的目的?

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.不久前我遇到了同样的问题,问题出在我试图拉入成功回调的数据中,我只是删除了静态变量,因此我试图进入 json 并严格保持其值仅从查询结果。 Maybe it's the same for you.也许对你来说也是一样。

You could use the ajax dataType property to interprate JSON directly after ajax response like :您可以使用 ajax dataType属性在 ajax 响应后直接解释 JSON,例如:

$.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:向您的 ajax 函数添加一个“错误”回调,然后打印内容:

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

This will show you what ajax is trying to parse as json.这将向您展示 ajax 试图解析为 json 的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM