问题
I am using KnockoutJS with SammyJS for one page application.
In the html I have form tag as follow
<form data-bind='submit: search'>
<label>Find user:</label>
<input data-bind='value: name' />
</form>
and in my viewmodel, declared two functions and sammy route url
function ViewModel() {
var self = this;
self.name = ko.observable("");
self.search = function () {
alert(self.name);
};
Sammy(function () {
this.get('#:id', function () {
//do something....
});
}).run();
}
ko.applyBindings(new ViewModel());
All code works good, until I type something in textbox then submit the form. I expected no url browsing after alert window, but url is changed to something like this "http://localhost:8258/undefined?" my original url is "http://localhost:8258"
I doubted sammy url routing, so removed sammy code from javascript code, then url does not change after alert window. Maybe I do not understand how sammy works.
How to prevent url change it this case?
回答1:
Sammy binds itself to forms to enable you to register routes for them as well.
<form action="#1234" method="post">
JS:
Sammy(function() {
this.post('#:id', function() {
// do something...
return false; // avoid form submission
});
// ...
}).run();
回答2:
I also had this problem and I found a solution in this answer. Here is how you can make Sammy.js to leave the forms alone:
Sammy(function() {
// Your routing..
this.get('#:id', function () {
//do something....
});
// Make Sammy.js leave the forms alone!
this._checkFormSubmission = function(form) {
return false;
};
}).run();
Works like it should :)
来源:https://stackoverflow.com/questions/10652881/how-to-prevent-form-submit