我知道有一个用 jQuery 解析 JSON 的快捷方式,例如
$.post('myPhpFile.php', postData, function(data){
console.log(data.status) // "OK"
},'json');
但我真的很讨厌匿名函数,而且我也很讨厌每次都必须手动解析 JSON。我希望我能做到这一点(因为我并不总是用相同的数据做同样的事情)
function getSomeData(phpFile, postData){
return $.post(phpFile, postData);
}
getSomeData.done(function(data){
console.log(data.status) // error, as is not JSON
},'json');
但是在 .done() 中,我必须首先 $.parseJSON(data),而且我有很多这样的小函数,它们只是返回 $.posts。
是否有任何其他快捷方式或良好的功能方式仍然返回 $.post 的延迟对象并且数据已经解析为 json ?我想到了
function getSomeData(phpFile, postData){
var defer = $.Deferred();
$.post(phpFile, postData, function(data){
defer.resolve(data);
},'json');
return defer.promise(data);
}
但我有强制症,现在我有两次延期。只是好奇是否有更好的方法。
最佳答案
如果您想传递 json
dataType 字段,但想使用 Promises 而不是匿名回调,只需为回调传递 null
即可。
来自docs :
A callback function that is executed if the request succeeds. Required if
dataType
is provided, but can benull
in that case
因此您需要的是:
function getSomeData(phpFile, postData) {
return $.post(phpFile, postData, null, 'json');
}
当然,如果您的服务器使用适当的 Content-type:
字段进行响应,那么 JQuery 无论如何都会很乐意猜测数据类型。
关于javascript - jQuery 在 .done() 函数中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679256/