Javascript 在提交表单并将结果写入字段之前验证表单提交,然后将提交该字段-使用Prevent default和Ajax请求
当我按下表单提交按钮时,我希望在表单实际提交之前,通过Ajax调用进行一些验证,并更改屏幕值 我的问题是,当我尝试此操作并手动操作Submit按钮时,屏幕值在表单提交之前不会实际更新。太晚了 有办法解决这个问题吗?我试着在代码中注释我的意思Javascript 在提交表单并将结果写入字段之前验证表单提交,然后将提交该字段-使用Prevent default和Ajax请求,javascript,jquery,ajax,forms,Javascript,Jquery,Ajax,Forms,当我按下表单提交按钮时,我希望在表单实际提交之前,通过Ajax调用进行一些验证,并更改屏幕值 我的问题是,当我尝试此操作并手动操作Submit按钮时,屏幕值在表单提交之前不会实际更新。太晚了 有办法解决这个问题吗?我试着在代码中注释我的意思 $("form").submit(function (event) { // we prevent teh default action of the udpate button event.preventDefault(); alert('In
$("form").submit(function (event) {
// we prevent teh default action of the udpate button
event.preventDefault();
alert('In Jquery/JS.. button pressed / Prevented default');
// variables for "self" so we can access the form
// nativley using javascript and not jquery
var self = this,
root = 'https://jsonplaceholder.typicode.com';
// Now call Ajax, get results, and if good, manually call the
// submit button.
$.ajax({
url: root + '/posts/1',
method: 'GET',
success: function (data) {
alert('in ajax success');
}
}).done(function (data) {
alert('in ajax done - Title data = : ' + data.title);
if (data.title !== "") {
// We assign our Input Text field some data
$('#textfield').val(data.title);
// The on screen value actually hasn't updated :o(
alert('about to self submit');
// We go to submit... but our form isn't actually
// updated with the Ajax text yet...
// is that possible before we action the submit???
self.submit();
}
}).fail(function () {
alert('error');
});
});
请参见JSFIDLE:这不是您所想的。因此,alert语句将在其上一条语句之后执行。它不会等待上一条语句完成
除此之外,警报比在文本框中设置值更快,它实际上会阻止线程,直到它被解除。这就是为什么您无法看到文本框中设置的值,但可以先看到提交警报
你的小提琴很好,它应该能正常工作。例如,如果要测试这一点,请尝试从代码中删除所有警报语句,并尝试将表单提交到实际的URLhttps://www.google.com.
虽然提交到Google会导致错误,但实际上您可以看到文本框在提交前已填充。在提交前使用jquery validato插件验证您的表单谢谢您提供的信息-但我仅限于客户端可以调用的脚本。不过我会查出来的。谢谢你-我已经更新了提琴,以显示提交的表单和传递的正确数据。