【发布时间】: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(' C'mon! Don'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 响应(我在问题中提到的那个),但之后当我解析它时,我会收到undefined。Success现在在我的脚本的其他功能中工作。所以我稍后会更新到.done。 -
我收到
[{"responseCode":1,"msg":"Successfully done!"}]提醒data -
你不需要解析它,只需执行 alert(data[0].responseCode);
-
@farhadamjady 随后的序列化和反序列化看起来绝对错误。
标签: javascript jquery json ajax