在AJAX成功但未解析时收到JSON响应

时间:2016-12-25 07:30:50

标签: javascript jquery json ajax

我在下面有以下AJAX功能。问题是我在AJAX的成功函数中得到了正确的响应头,但是当我解析响应时,我得到了[{"responseCode":1,"msg":"Successfully done!"}]

我收到的JSON数据如下:

// 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;
    });

JS

    private JMenuItem composeMenuItemFromActionOfComponent(String actionTag, JComponent component, String text, String idTag){
    Action action = component.getActionMap().get(actionTag);
    JMenuItem menuItem = new JMenuItem(action);
    menuItem.setText(text);
    menuItem.putClientProperty("id",idTag);
    if(action == null)
        menuItem.setEnabled(false);
    return menuItem;
}
private void addTextMenuItems(JTextComponent textField){
    final JPopupMenu popup = new JPopupMenu();
    if(textField.isEditable()) {
        popup.add(composeMenuItemFromActionOfComponent("undo", textField, "Undo", "undo"));
        popup.addSeparator();
    }
    popup.add (composeMenuItemFromActionOfComponent(DefaultEditorKit.copyAction,textField,"Copy", "copy"));
    if(textField.isEditable()) {
        popup.add(composeMenuItemFromActionOfComponent(DefaultEditorKit.cutAction, textField, "Cut", "cut"));
        popup.add(composeMenuItemFromActionOfComponent(DefaultEditorKit.pasteAction, textField, "Paste", "paste"));
        popup.addSeparator();
    }
    popup.add (composeMenuItemFromActionOfComponent(DefaultEditorKit.selectAllAction,textField,"Select All", "select_all"));

    textField.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {}

        @Override
        public void mousePressed(MouseEvent e) {}

        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()) {
                boolean isTextSelected = textField.getSelectedText() != null;
                for(MenuElement element : popup.getSubElements()){
                    JMenuItem menuItem = ((JMenuItem) element);
                    if(menuItem.getAction() != null && menuItem.getAction().isEnabled()) {
                        if (isTextSelected){
                            menuItem.setEnabled(true);
                        }else if (!(menuItem.getClientProperty("id").equals("select_all")
                                || menuItem.getClientProperty("id").equals("undo")))
                            menuItem.setEnabled(false);
                    }
                    if(menuItem.getClientProperty("id").equals("paste")){
                        boolean isPastAvailable = false;
                        for(DataFlavor flavor : Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors()){
                            if(flavor.getRepresentationClass() == String.class){
                                isPastAvailable = true;
                                break;
                            }
                        }
                        menuItem.setEnabled(isPastAvailable);
                    }

                }
                e.getComponent().requestFocus();
                popup.show(e.getComponent(), e.getX(), e.getY());
            }

        }

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}
    });
}

2 个答案:

答案 0 :(得分:3)

解析响应时,它将转换为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!"} 

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

答案 1 :(得分:1)

如果指定dataType:“text”,则不会解析响应。 巡回期望的问题是您尝试访问数组的属性:

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

obj是一个数组! (或删除e Square brakets!)