How to handle form error state in jQuery Mobile and return HTML?
What is the best way to handle forms in jqm?
For example, lets say the user fills out a form and some of the data doesnt validate. Its 开发者_StackOverflow社区not picked up by the JS validation but it does trigger some business logic meaning that the system cannot proceed.
In jqm, the form would be returned to the user and the framework would load it up and navigate to it. Expect, I don't want it to be navigated to as its not a new state - I just want it to show the updated form with error message. I don't want to disable ajax either, as that adds an unnecessary full page reload.
Ideally, what I would like is a way to tell jqm not to transition or include the response in the history - rather just show it in place of what is there.
The only way I can see this working is to write my own little form handler and return JSON from the server, which includes an error state. If submission was good navigate to the next page, otherwise update the html in the view with the html returned as part of the JSON object which includes any error messages.
Seems there must be a better way though?
Thanks
Good question and I too would be interested to see what others have to say. For what it's worth, in a recent app (which also had to work off-line), I went down your proposed route with my forms:
- Prevented the default submit action.
- Used an ajax call from a button, which checks data before submitting it either to a web service, or simply saving to the local database (depending on a status flag and whether we're on-line or not).
- Ensure that all relevant success / fail messages trickle back up through the submit callback so that we can…
- … update the same html page with the results of the user submission.
This works well, and the users are happy. However, it fits my particular set of circumstances—I didn't want to use any querystring / location.hash
stuff because (a) jQM sometimes freaks out with hashes and, (b) potentially the user will be off-line (and no web server means no querystring). Your mileage may vary of course.
EDIT: code to update a page with messages
For my app I wanted a list of messages to appear in the current page when required, so I have an empty unordered list (messages
) in the relevant HTML page, which in turn sits inside a styled div (message-pane
). Here's a code snippet showing how the update happens (note the refresh
call, which is required in jQM). You could trigger some code like this from your ajax handler:
var list = $("#messages");
list.append('<li>YOUR MESSAGE HERE</li>');
list.listview('refresh');
$("#message-pane").show();
精彩评论