简体   繁体   English

使用原型通过Ajax提交表单并更新结果div

[英]submit a form via Ajax using prototype and update a result div

I'm wondering how can I submit a form via Ajax (using prototype framework) and display the server response in a "result" div. 我想知道如何通过Ajax(使用原型框架)提交表单并在“结果”div中显示服务器响应。 The html looks like this : html看起来像这样:

<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). 我试图将一个javascript函数(使用Ajax.Updater)附加到“onsubmit”(在表单上)和“onclick”(在输入上)但是在函数结束后表单仍然是“非Ajax”(所以整个页面被结果替换)。

Check out Prototype API's pages on Form.Request and Event handling. Form.RequestEvent处理上查看Prototype API的页面。

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: 你的js会或多或少:

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
});

You need to return the value false from the ajax function, which blocks the standard form submit. 您需要从ajax函数返回false值,该函数会阻止标准表单提交。

<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. 在表单上使用onsubmit还会捕获使用回车键提交的用户。

You first need to serialize your form , then call an Ajax Updater , using POST options and pass it the serialized form data. 首先需要序列化表单 ,然后使用POST选项调用Ajax更新程序并将序列化表单数据传递给它。 The result will then appear in the element you sepcified. 然后结果将出现在您分离的元素中。

You need to stop the default action of the onsubmit event. 您需要停止onsubmit事件的默认操作。

For example: 例如:

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

More info on stopping default event behavior in Prototype » 有关在Prototype中停止默认事件行为的更多信息»

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM