我一直在找我在这里找到的Ajax上传教程。我正在尝试检查服务器是否"error"
作为状态返回。我发现了,是data.result
。当我这样做console.log(data)
的时候data
被定义,result
被{"status":"error"}
预期,但是当我尝试打电话给data.result
在同一个函数,它返回undefined。我尝试了所有操作,在未定义全局变量时将其定义,甚至将其传递给另一个函数。这是我所拥有的:
progress: function(e, data){
// calc the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
console.log(data);
/* console log:
Object {disabled: false, create: null, dropZone: b.fn.b.init[1], pasteZone: b.fn.b.init[1], replaceFileInput: true…}
(more values)
result: "{"status":"error"}"
(more values)
*/
// update hidden input field and trigger a change
data.context.find('input').val(progress).change();
if(progress == 100){
updateProgress(data);
}
},
// ... later on in the file ...
function updateProgress(data){
console.log(data);
if(JSON.parse(data.result).status === 'error'){
data.context.addClass('error');
}else{
data.context.removeClass('working');
$('#drop').fadeOut(function(){
$('#drop').remove();
if(debug === 0){window.location = 'http://datastorage.iquestria.net/images/'+data.files[0].name+'?v2';}
});
}
}
经过多番讨论,最终的问题data.result
是只能在done
回调中可靠地使用,而在progress
OP试图访问它的回调中则无法可靠地使用。
您的Ajax调用的结果只能在提供数据的回调中使用。您不能在其他任何地方使用它。这是因为回调是异步调用的,并且在函数的其余部分已经完成之后的某个时候结束。
有关更多详细信息,请参见此答案:如何从异步调用返回响应?
另外,如果您正确使用了jQuery的ajax调用,则您无需进行任何JSON解析,因为jQuery会为您完成所有这些工作。我不太清楚您得到的结果是什么,但是如果您为ajax调用指定正确的数据结果类型,则jQuery会自动为您解析它,而您不必JSON.parse()
自己调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句