gpt4 book ai didi

javascript - AJAX 成功收到 JSON 响应但未解析

转载 作者:行者123 更新时间:2023-11-30 09:40:37 25 4
gpt4 key购买 nike

我在下面有以下 AJAX 函数。问题是我在 AJAX 的成功函数中得到了正确的响应 header ,但是当我解析响应时我得到了 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;
});

最佳答案

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

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

关于javascript - AJAX 成功收到 JSON 响应但未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com