gpt4 book ai didi

javascript - 使用 jQuery 处理表单数据

转载 作者:行者123 更新时间:2023-11-30 09:09:55 25 4
gpt4 key购买 nike

我目前正在使用 Prototype,但我想将此函数重写为 jQuery:

function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}

附带的 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>

我一直在查看 jQuery.load() 和 jQuery.post(),但我不确定应该使用哪一个以及如何使用。

预先感谢您的帮助。

最佳答案

使用这个 HTML:

<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>

你可以用 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
});
});

我摆脱 onsubmit 代码的原因是因为这样的内联 JavaScript 被认为是不好的做法。您应该努力使您的表单摆脱 JavaScript,然后将所有 JavaScript 与其绑定(bind)。这被称为不显眼的 JavaScript,这是一件好事。

编辑:

由于您在许多页面中都有该代码,因此该函数将使用您当前在 post 函数上具有的相同签名来执行您想要的操作。我建议您花几个小时来更新所有表格,而不是保留它,但无论如何它都在这里:

function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}

就您的问题而言,livequery插件可以帮助你。或者,它就像将绑定(bind)代码封装在一个函数中并在添加表单时调用它一样简单。

关于javascript - 使用 jQuery 处理表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/941714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com