开发者

getJSON triggered from a button inside a form

开发者 https://www.devze.com 2022-12-29 11:48 出处:网络
I\'m having trouble understanding why I have to place the button triggering the getJSON method outside of the form for the request to work.

I'm having trouble understanding why I have to place the button triggering the getJSON method outside of the form for the request to work.

If the button is placed within the form then the getJSON method returns no results.

The code bascially makes a XHR request on clicking the Submit button, based on the value selected. I have replicated the issue here: http://jsfiddle.net/z6c开发者_Python百科aj/

Many Thanks,


The clicking of the button will submit the form the normal way (when placed inside the form). return false at the end of your click handler, and it should work as expected. Alternatively, prevent submission by making the form's submit handler return false:

$("form").submit(function() {
    return false;
});


Because it is a submit button and you do nothing to prevent the default action.

So the JS runs (setting the Ajax request going) and then the form submits (leaving the page and throwing the request away).

See http://docs.jquery.com/Tutorials:How_jQuery_Works (the section starting "For click and most other events")


You could actually do the ajax request on the dropdown using the onchange event e.g.

$('#state').change(function(){

     //do stuff

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号