我在提交 JQM 表单时也遇到了问题(主要是试图阻止它)。最终我用普通的替换了我的表单提交按钮<input>
一个按钮将调用一个处理程序:
<input type="button" class="fake_submit" onclick="my_handler()" data-role="button" data-theme="e" data-icon="arrow-r" />
将handler
获取表单内容,修改所需内容并调用我的全局submitter
:
我的处理程序将是这样的(你也可以on('click', '.fake_submit', function...
)
myHandler = function () {
// get the form
var form = $(this).closest('form'),
// custom parameter, I'm creating to route on server side
switcher = form.find('input[name="form_submitted"]').val(),
// which url to call
urlToCall= "../services/form_xyz.cfc",
// custom parameter, which method to call server-side
method = "process",
// override default GET
type = "post",
// we expect JSON
returnformat = "JSON",
// in case we want to changePage when we have the result
targetUrl = "",
// serialize the form and attach custom parameters
formdata = form.serialize()+"&method="+method+"&returnformat="+returnformat,
// run this function on success
successHandler = function() {
// for example
switch (switcher) {
case "login":
// refersh application to prevent backbutton
window.location = 'index.html';
break;
case "logout":
window.location = 'login.html';
break;
case "forget":
$.mobile.changePage('lost.html', {transition: 'fade' });
break;
case "message_sent":
$.mobile.changePage( 'thanks.html', {transition: 'pop', role: "dialog" });
break;
}
};
// call the global ajaxhandler
ajaxFormSubmit( form, urlToCall, formdata, targetUrl, successHandler, null, "", returnformat, type );
// for good measure (and because I also started to be paranoid about awol-submits...
return false;
});
};
和提交者:
var ajaxFormSubmit =
function (
form,
urlToCall,
formdata, // serialized form data
targetUrl, // I think I'm not using this at all...
successHandler, //
dataHandler, // true/false > does the success function require the response sent back
errorHandler, // function to be run on server-side errors
returnformat,
type // override default GET if needed
){
$.ajax({
async: false,
type: type == "" ? "get" : type,
url: urlToCall,
data: formdata,
dataType: returnformat,
success: function( objResponse ){
// I'm passing back string or object from the server
if (objResponse.SUCCESS == true || typeof objResponse == "string" ){
// we need the data returned to continue?
dataHandler ? successHandler( objResponse ) : successHandler();
} else {
// server side error
if ( errorHandler !== "" ){
errorHandler();
}
}
},
// ajax error
error: function (jqXHR, XMLHttpRequest, textStatus, errorThrown) {
console.log(error);
}
});
}
我做了一个相当复杂的应用程序,我正在以这种方式提交所有表单。工作没有错误。如果您对上述内容有任何疑问,请告诉我。