我有完全相同的问题,我写了POST ajax调用的包装。这个想法是,当你尝试开机自检时,它首先会向简单的ping.php发出一个GET请求,并且只有在成功后才会请求POST。
下面是它的外观中的骨干观点:
var BaseView = Backbone.View.extend({
ajax: function(options){
var that = this,
originalPost = null;
// defaults
options.type = options.type || 'POST';
options.dataType = options.dataType || 'json';
if(!options.forcePost && options.type.toUpperCase()==='POST'){
originalPost = {
url: options.url,
data: options.data
};
options.type = 'GET';
options.url = 'ping.php';
options.data = null;
}
// wrap success
var success = options.success;
options.success = function(resp){
if(resp && resp._noNetwork){
if(options.offline){
options.offline();
}else{
alert('No network connection');
}
return;
}
if(originalPost){
options.url = originalPost.url;
options.data = originalPost.data;
options.type = 'POST';
options.success = success;
options.forcePost = true;
that.ajax(options);
}else{
if(success){
success(resp);
}
}
};
$.ajax(options);
}
});
var MyView = BaseView.extend({
myMethod: function(){
this.ajax({
url: 'register.php',
type: 'POST',
data: {
'username': 'sample',
'email': '[email protected]'
},
success: function(){
alert('You registered :)')
},
offline: function(){
alert('Sorry, you can not register while offline :(');
}
});
}
});
有你的清单是这样的:
NETWORK:
*
FALLBACK:
ping.php no-network.json
register.php no-network.json
文件ping.php很简单,只要:
<?php die('{}') ?>
而no-network.json看起来像这样:
{"_noNetwork":true}
然后你去了,在任何POST之前,它将首先尝试GET ping.php并在离线状态下调用offline()。
希望这有助于;)