【问题标题】:JSON response received in AJAX success but not parsing在 AJAX 成功中收到 JSON 响应但未解析
【发布时间】:2026-02-05 10:45:02
【问题描述】:

我在下面有以下 AJAX 函数。问题是我在 AJAX 的成功函数中获得了正确的响应标头,但是当我解析响应时,我得到了 undefined

我收到的 JSON 数据如下:

[{"responseCode":1,"msg":"Successfully done!"}]

JS

// Renaming am item
    filelist.on('click', '.btn-rename', function(){
        var that = this; //Save the scope of the button that was clicked
        var id = $(this).data('id');
        var name = $(this).data('filename');
        var jc = $.confirm({
            theme: 'black',
            type: 'dark',
            typeAnimated: true,
            title: 'Rename this file?',
            icon: 'fa fa-pencil-square-o',
            content: '<input id="newName" type="text" value="'+name+'"/><span id="response"></span>',
            onOpen: function() {
                var element = $('#newName');
                element.focus();
                element.select();
            },
            buttons: {
                save: {
                    text: 'Rename',
                    btnClass: 'btn-dark',
                    action: function() {

                        this === jc;

                        var inputName = $('#newName').val();
                        if(inputName == '') {
                            $('#response').html('Please enter a new name..').addClass('responseAlert');
                            return false;
                        }
                        else
                        if(inputName == name) {
                            $('#response').html('&nbsp;C&#39;mon! Don&#39;t be silly..').addClass('responseWarning');
                            return false;
                        }

                        //Send request to update the name
                        $.ajax({
                            type:"POST",
                            url:"rename.php",
                            data: {
                                fileId: id,
                                newName: inputName
                            },
                            beforeSend: function() {
                                $('#response').html('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i> Working on it...').addClass('responseProcessing');
                            },
                            success: function(data){
                                var obj = JSON.parse(data);
                                var status = obj.responseCode;
                                alert(obj.responseCode);
                                if(status == 1) {
                                    jc.close();
                                    $.alert({
                                        theme: 'black',
                                        icon: 'fa fa-check',
                                        title: 'Success',
                                        type: 'green',
                                        typeAnimated: true,
                                        content : response.msg
                                    });
                                }
                                else {
                                    $('#response').html(response.msg).addClass('responseAlert');
                                }
                            }
                        });
                        return false;
                    }
                },
                cancel: {
                }
            }
        });
        return false;
    });

【问题讨论】:

  • 您是否尝试在success 开头设置断点? data 是什么?可能,它已经被 jQuery 解析了。另外,请注意success 是一个已弃用的功能,请使用.done
  • 如果我提醒 data,我会收到 JSON 响应(我在问题中提到的那个),但之后当我解析它时,我会收到 undefinedSuccess 现在在我的脚本的其他功能中工作。所以我稍后会更新到.done
  • 我收到[{"responseCode":1,"msg":"Successfully done!"}] 提醒data
  • 你不需要解析它,只需执行 alert(data[0].responseCode);
  • @farhadamjady 随后的序列化和反序列化看起来绝对错误。

标签: javascript jquery json ajax


【解决方案1】:

解析响应时,它会转换为 JSON 数组,并将该对象作为第一个元素进行索引。请注意括号[] 导致了这种情况。

var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object] 
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}

var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object] 
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}

而解析没有括号的字符串会产生所需的对象

var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"} 

var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"} 

您需要从后端删除这些括号。

【讨论】:

    【解决方案2】:

    如果您指定 dataType:"text",则响应将不会被解析。 旅游期望的问题是您尝试访问数组的属性:

    var data = "[{"responseCode":1,"msg":"Successfully done!"}]"
    var obj = JSON.parse(data)
    // and then:
    console.log(obj[0]. responseCode)
    

    obj 是一个数组! (或删除 e 方括号!)

    【讨论】: