【问题标题】:Uncaught (in promise) SyntaxError: Unexpected end of JSON input for JSON data processing received form Django backendUncaught (in promise) SyntaxError: Unexpected end of JSON input for JSON data processing received from Django backend
【发布时间】:2021-08-23 19:04:51
【问题描述】:

我使用 Django 开发了一个网络应用程序。

我想将JSON格式的sting数据(msg)发送到前端,然后将后端发送的JSON数据处理为字符串,然后在javascript中的if条件下比较这个字符串。

view.py:

    @csrf_exempt
def content_checklist_name_url(request):
    msg = "Duplicate Entry. This Course Code already exists."
    json_data = {'msg': msg}
    return JsonResponse(json_data)

Javascript:

                       $.ajax({     
        url: '/content_checklist_name_url/',  
        type: 'POST',           
        data: $("#myform").serialize(),           
        cache: false,       
        success: function (data) {        
       
    
            var comment_html = "<div id='myform1'>" + data['log_info'] + "</div>";
            $('#myform1').remove();
            $('#ajax_data').prepend(comment_html);
            $('#myform_input').val('');
        },

    });


            const response = await fetch({% url 'bms:content_checklist_name_url' %});   

            var msg_json = jQuery.parseJSON(response.msg);

...

当我尝试接收和处理从后端发送的 JSON 数据时,出现错误:Uncaught (in promise) SyntaxError: Unexpected end of JSON input 在 Function.parse [as parseJSON] ()

当我调试时,我发现 POST 这个 URL 被发送了两次,而在第二次,msg 是 none。 那么可能是 JSON 的 none 值导致了这个错误,但是为什么它发送了两次 POST 请求呢?

【问题讨论】:

    标签: javascript json django


    【解决方案1】:

    我认为错误在“{{json_data}}”中

    var msg_json = jQuery.parseJSON("{{json_data}}");

    你应该这样做

    var msg_json = jQuery.parseJSON(response.msg);

    【讨论】:

    • 试过你的解决方法,还是一样的错误
    • 我认为您的 json 存在语法错误,请检查您的服务器返回的内容
    猜你喜欢
    • 2021-11-06
    • 2019-08-31
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2019-11-21
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多