1

我有以下脚本。出错时,它通过显示一个模态来工作,我已经对此进行了测试并且它可以工作。成功后它应该显示一个警告框,但我收到消息:

SyntaxError: JSON.parse: unexpected end of data

这是引发错误的行:

data = JSON.parse(errorThrown.responseText);

但是,它不应该成功运行它吗?

有人可以看看吗?

201 CREATED页面按原样返回成功。

$.ajax({
        url: '/accounts/create/',
        type: 'POST',
        dataType: "json",
    },
    data: $('#registration').serialize(),
    success: function () {
        console.log('success');
        alert("test")
    },
    error: function (errorThrown) {
        data = JSON.parse(errorThrown.responseText);
        $('#account-error').modal("show");
        $('#error-text').html(data.error);
        console.log(errorThrown);
    }
});
4

2 回答 2

4

问题在于数据类型。错误将是 json 但看起来您的成功 dataType 不是。这意味着它会再次触发“错误”功能。只需删除 dataType 看看会发生什么。

于 2013-10-16T16:43:20.937 回答
0

您尝试解析为 JSON 的数据不是JSON 格式的

您可以使用

if(typeof jQuery.parseJSON(errorThrown.responseText)==="object")

检测响应文本是否为有效的 JSON 格式!

希望这可以帮助!

编辑

您可能想尝试使用jQuery.post()

var ajaxRequest = jQuery.post("/accounts/create/", $('#registration').serialize(), function() {
  //On success
})
  .fail(function(errorThrown) {
    data = errorThrown.responseText;
    $('#account-error').modal("show");
    $('#error-text').html(data.error);
    console.log(errorThrown);
  });

您正在尝试 JSON 解析 Javascript 对象,当您在 ajax 请求中指定 dataType 时,响应已经从 Json 转换为 Javascript 对象。

于 2013-10-16T16:16:50.803 回答