我正在尝试学习javascript最佳做法,我有些困惑。我认为最好的ajax做法是:
function doSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST"
}).done(function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
});
}
而不是这样:
function getSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST",
success: function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
}
});
}
我问哪种做法最好,为什么?
最佳答案
两种方法都很好,只是使用success
回调或promise的区别,在这种情况下没有区别。如果要从函数doSomething
返回结果,则可以使用第一种方法,以便可以返回promise,因为可以将done
方法绑定到函数外部。
这两个示例都过于复杂,并且var urlink = resourceURL
放在对象文字内部,因此两者均无法正常工作。您还应该在调用中指定dataType
,然后将自动分析数据。
在第一个示例中,您不需要额外的函数包装器。
function doSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json"
}).done(function(data) {
updateHtml1(data);
updateHtml2(data);
});
}
第二个应该是:
function getSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json",
success: function(data) {
updateHtml1(data);
updateHtml2(data);
}
});
}
关于javascript - 什么是AJAX最佳做法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28431236/