根据从ajax调用收到的响应阻止表单提交 [英] Prevent form submission based on the response received from ajax call

查看:93
本文介绍了根据从ajax调用收到的响应阻止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,一旦单击 submit 类型的 input 即可提交.现在,我想添加一个验证,以便如果数据库中已经存在唯一ID,则应该显示警报消息,并且不应该提交表单.为此,我使用Ajax来检查唯一ID的存在,这是我的ajax代码:函数validate(){$ .ajax({输入:"POST",网址:"/Controller/Method",数据:'{条形码:'+条形码+'"}',contentType:"application/json,charset = utf-8",数据类型:"json",成功:功能(响应){//在这里我要显示警报消息//和一些代码以停止表单提交.}});}

I have a form which gets submitted once the input of type submit button is clicked. Now i want add a validation such that if an unique ID is already exists in the database then the a alert message should display and form should not be submitted. For this I am using Ajax to check the existence of Unique ID, here is my ajax Code: function validate(){ $.ajax({ type: "POST", url: "/Controller/Method", data: '{barcode:"' + barcode + '"}', contentType: "application/json,charset=utf-8", datatype: "json", success: function (response) { //here i want to display the alert message // and some code to stop the form submission. } }); }

这是我的输入按钮代码:< input type ="submit" value ="Go" onclick ="return validate()"/>

Here's my input button code: <input type="submit" value="Go" onclick="return validate()" />

我尝试了 return false ,但是它不起作用.

I have tried return false but it is not working.

推荐答案

双重否定逻辑以使用异步代码得出解决方案.如果ID已存在,则不要停止提交表单,而仅在不存在时才提交表单.

Double negate the logic to arrive at a solution using asynchronous code. Instead of stopping form submission if the id exists already, only submit the form if it doesn't.

正如注释中指出的那样,如果ID是在第一次检查ID存在与尝试基于仍然不存在的情况下尝试处理表单数据之间的时间创建的,则仍需要服务器上的逻辑来生成错误以提交表单不存在.

As pointed out in comment you would still need logic on the server to generate an error for form submission if the id was created in the time between first checking it existed and attempting to process form data based on the assumption it still doesn't exist.

最好在单个服务器请求中提交表单数据和ID.

It may be better to submit form data and the id in a single server request.

这篇关于根据从ajax调用收到的响应阻止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆