自定义jQuery Ajax函数问题排查:无failcmds时失败分支误执行成功代码
排查你的jQuery Ajax函数问题
我来帮你一步步梳理这个问题,核心问题其实有两处,还有一个潜在的坑需要注意:
1. 示例代码里提前执行了回调函数
你看这段示例代码:
var sarr = [reload(2500)];
这里你直接写了reload(2500),这会立刻执行这个函数,不管后面的Ajax请求成功还是失败。这也是你误以为“进入succcmds代码块执行reload”的主要原因——其实它在调用gr函数之前就已经跑起来了。
正确的做法是把它封装成一个匿名函数,让它只有在Ajax触发succcmds时才执行:
var sarr = [function() { reload(2500); }];
2. gr函数里的回调执行逻辑错误
在你的gr函数中,处理succcmds和failcmds时,只是写了val;或者value;,这相当于只是引用了函数,并没有实际调用它。比如这段:
$.each(succcmds,function(ind, val) { val; });
要真正执行回调函数,必须加上():
$.each(succcmds,function(ind, val) { val(); });
同理,failcmds的处理也要改成value();。
3. 潜在的JSON解析问题
如果后端返回的响应头设置了Content-Type: application/json,jQuery会自动把response解析成JSON对象,这时候你再执行$.parseJSON(response)会报错,导致obj变成无效值,进而跳过status的判断逻辑。可以加个判断兼容两种情况:
var obj = typeof response === 'object' ? response : $.parseJSON(response);
验证逻辑流程
当后端返回obj.status == "failure"且未传入failcmds时,你的代码里已经有return;语句,理论上会直接跳出success回调,不会进入succcmds分支。之前的问题主要是因为提前执行了reload,加上回调执行的写法错误导致的误解。
修改后的完整代码
修正后的示例用法
$(document).on("click", '.xyz', function() { var d = $(this).prop('id'); var data = 'd='+ $(this).prop('id') + '&typ=sts'; gm('c','Are you sure you want to do this?'); $(document).on("click", '#btnYes', function() { // 封装成匿名函数,避免提前执行 var sarr = [function() { reload(2500); }]; gr(basepath + "deletereq?", data, sarr); }); });
修正后的gr函数
function gr(url, varr, succcmds, failcmds, divid, drestype) { $.ajax({ url: url, type: "POST", data: varr, beforeSend: function(){ $('#loadingDiv').show(); }, complete: function(){ $('#loadingDiv').hide(); }, success: function(response){ if(response){ // 兼容自动解析和手动解析的情况 var obj = typeof response === 'object' ? response : $.parseJSON(response); // 确保响应格式正确 if(!obj || typeof obj.status === 'undefined') { gm("e", "Invalid response format"); return; } if(obj.status == "failure") { console.log('failcmds : ' + failcmds); if(obj.message) { gm("e",obj.message); } if(typeof failcmds !== "undefined") { $.each(failcmds,function(index, value) { value(); // 执行失败回调 }); } return; // 跳出,不执行后续成功逻辑 }else if(obj.status == "success"){ if(obj.message) { gm("s",obj.message); } if(succcmds && succcmds !== null) { $.each(succcmds,function(ind, val) { val(); // 执行成功回调 }); } if (divid && divid !== null){ if(drestype && drestype == "html"){ $("#"+ divid).html(obj.data); }else{ $("#"+ divid).append(obj.data); } } } else { gm("e", "Unknown response status"); } }else{ gm("e", "Invalid Request"); } }, error: function(){ // 建议添加网络错误处理 gm("e", "Request failed"); } }); }
内容的提问来源于stack exchange,提问作者techworld
相关产品推荐
相关产品推荐

