当前位置: 首页 > 工具软件 > End Admin > 使用案例 >

“parsererror“ SyntaxError: Unexpected end of JSON input 报错解决

百里俭
2023-12-01

问题

使用$.ajax调请求,接口200,但没有走success回调函数,反而进入了error报错。
原代码如下:

$('button[type=submit]').click(function () {

    if (!flag) return;

    let params = {
      mobile: mobile,
      extra: {
        landing_page: location.href,
      },
    };
    $.ajax({
      dataType: 'json',
      type: 'post',
      url: '/api/customer/add_sem',
      data: params,
      success: function (result) {
        console.log(result);
        toToast('联系方式提交成功')
      },
      error: function (xhr, textStatus, errorThrown) {
        console.log(xhr, textStatus, errorThrown);
        toToast('提交失败,请稍后重试~')
      }
    });
  })

打印error里的信息后,进行报错查询。发现是因为接口返回的json文件为空,(因为该接口是一个post新增接口,无需返数据到前端,所以后端没有进行设置)

解决

去掉dataType: 'json’选项。

$('button[type=submit]').click(function () {

    if (!flag) return;

    let params = {
      mobile: mobile,
      extra: {
        landing_page: location.href,
      },
    };
    $.ajax({
      type: 'post',
      url: '/api/customer/add_sem',
      data: params,
      success: function (result) {
        console.log(result);
        toToast('联系方式提交成功')
      },
      error: function (xhr, textStatus, errorThrown) {
        console.log(xhr, textStatus, errorThrown);
        toToast('提交失败,请稍后重试~')
      }
    });
  })

提交,OK!成功进入success回调。

 类似资料: