Ale*_*lec 1 javascript ajax jquery prototypejs
我目前正在使用Prototype,但我想将此函数重写为jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}Run Code Online (Sandbox Code Playgroud)
与它一起使用的HTML示例:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result"></div>Run Code Online (Sandbox Code Playgroud)
我一直在看jQuery.load()和jQuery.post(),但我不确定使用哪一个以及如何使用.
在此先感谢您的帮助.
使用此HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)
你可以用jQuery做到这一点:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
Run Code Online (Sandbox Code Playgroud)
我摆脱onsubmit代码的原因是因为像这样的内联JavaScript被认为是不好的做法.你应该努力使你的表单免于JavaScript,然后将所有的JavaScript绑定.这被称为不引人注目的JavaScript,它是一件好事.
编辑:
由于您在许多页面中都有该代码,因此这个函数可以使用您当前在post函数上使用的相同签名来执行您想要的操作.我建议您花几个小时来更新所有表格而不是保留这个,但不管怎么说:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
Run Code Online (Sandbox Code Playgroud)
就你的问题而言,livequery插件可以帮助你.或者,它就像在函数中封装绑定代码并在添加表单时调用它一样简单.
| 归档时间: |
|
| 查看次数: |
12725 次 |
| 最近记录: |