Is putting # in href the "right" way to do an HTTP POST from the onclick event?
I've seen many examples that put # in the href attribute of a link, in order to get the browser to fire the onclick event. I did this myself recently in a Ruby Sinatra application. Wha开发者_JAVA技巧t I'm noticing now is when I redirect to '/' from inside my server-side code (via a 303 response), the URL in the browser still has the # on the end.
Is this the "correct" way to do a post without a form element?
<a href='#' onclick="$.post('/test1/69')">add</a>
The correct approach is to use progressive enhancement. You should build on things that work.
In this case the best approach would probably to be to start with a <form>
containing a submit button. Then style them to look the way you want (so the form is inline and the button is like a link). Then add a submit
handler with unobtrusive JS to AJAXify it.
My preference is to have the click event fire a method that does the post and also returns false, preventing event propagation that would cause the link to actually be followed. When you do this, it doesn't matter what you put in the href, because it won't be used.
That is very old way of doing you can probably do like this
<a class="test">add</a>
$('.test').click(function() {
//you can do your logic here and say
return false;//it will do both stoppropagation and event.preventDefault
});
http://api.jquery.com/event.preventDefault/
http://api.jquery.com/event.stopPropagation/
I prefer divs if there are click events when compared to a hrefs
精彩评论