submit a form via Ajax using prototype and update a result div

旧巷老猫 提交于 2019-11-30 14:04:59

问题


I'm wondering how can I submit a form via Ajax (using prototype framework) and display the server response in a "result" div. The html looks like this :

<form id="myForm" action="/getResults">
    [...]
    <input type="submit" value="submit" />
</form>
<div id="result"></div>

I tried to attach a javascript function (which uses Ajax.Updater) to "onsubmit" (on the form) and "onclick" (on the input) but the form is still "non-Ajax" submitted after the function ends (so the whole page is replaced by the results).


回答1:


Check out Prototype API's pages on Form.Request and Event handling.

Basically, if you have this:

<form id='myForm'>
.... fields ....
<input type='submit' value='Go'>
</form>
<div id='result'></div>

Your js would be, more or less:

Event.observe('myForm', 'submit', function(event) {
    $('myForm').request({
        onFailure: function() { .... },
        onSuccess: function(t) {
            $('result').update(t.responseText);
        }
    });
    Event.stop(event); // stop the form from submitting
});



回答2:


You first need to serialize your form, then call an Ajax Updater, using POST options and pass it the serialized form data. The result will then appear in the element you sepcified.




回答3:


You need to return the value false from the ajax function, which blocks the standard form submit.

<form id="myForm" onsubmit="return myfunc()" action="/getResults">


function myfunc(){
   ... do prototype ajax stuff...
  return false;

}

Using onsubmit on the form also captures users who submit with the enter key.




回答4:


You need to stop the default action of the onsubmit event.

For example:

function submit_handler(e){
    Event.stop(e)
}

More info on stopping default event behavior in Prototype »



来源:https://stackoverflow.com/questions/443276/submit-a-form-via-ajax-using-prototype-and-update-a-result-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!