var App = {
actionRequest: function (url,data,callback){
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
that.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}
}
我需要在" .done"中调用refreshCart。如何在" .done"中编写回调函数?这样做?对不起,我是Ajax的新手。
答案 0 :(得分:1)
var object = {
actionRequest: function(url, data, callback) {
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
if ($.isFunction(callback)) {
callback();
}
$.mobile.loading('hide');
}
);
}
}
用法:
如果refreshCart
在对象中起作用,您也可以这样做:
var object = {
actionRequest: function(url, data, callback) {
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
// without using a callback
that.refreshCart();
$.mobile.loading('hide');
}
);
},
refreshCart: function() {
App.loadExternalContent('content', 'scripts/data_ajax.php', 'action=getCart', 'templates/cart.htm');
}
}
以下是如何使用ajax请求的示例
$.ajax({
url: 'http://echo.jsontest.com/title/ipsum/content/blah',
method: 'GET'
})
.done(function(response) {
console.log(response);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:1)
我假设你在课堂上引用这段代码。
actionRequest: function (url,data,callback){
var self = this; //keep reference of current instance for more info read closures in JS
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
self.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}
答案 2 :(得分:0)
Ajax功能:
actionRequest: function (url,data,callback){
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
callback();
$.mobile.loading('hide');
}
);
}
通话功能:
actionRequest(url, data, refreshCart);