简体   繁体   English

如何克服通过Ajax提交表单的弊端

[英]How to overcome disadvantages of submitting form via ajax

I have a form which usually has a hash. 我有一个通常带有哈希的表格。 I can submit the form the normal way and run the usual validation. 我可以按正常方式提交表格并运行常规验证。 If there are errors, the form re-renders and zend adds the usual errors. 如果有错误,该表单将重新渲染,然后zend添加通常的错误。 It seems that submitting forms with ajax (jQuery) means that I lose all this validation, which I'm sure was already addressed before. 似乎使用ajax(jQuery)提交表单意味着我失去了所有此验证,我确信之前已经解决了这一问题。 How do you get the same validation and handle the errors when doing ajax submissions? 在进行ajax提交时,如何获得相同的验证并处理错误?

I used to worry about the hash element, but what I discovered is that it seems to not matter for ajax forms submissions. 我曾经担心过hash元素,但是我发现对ajax表单提交似乎无关紧要。 So that's one out of the way. 因此,这就是其中之一。

Handling validation with an AJAX for is a two-step process. 使用AJAX处理验证过程分为两个步骤。 First you should incorporate comprehensive frontend validation. 首先,您应该合并全面的前端验证。 This should alert the user to issues prior to actually making the AJAX call. 这应该提醒用户在实际进行AJAX调用之前遇到的问题。

Second include standard validation on the server. 其次包括服务器上的标准验证。 If this fails you can simply generate a 404 not found or 400 bad request because someone is attempting to send data without going through the frontend validation. 如果失败,您可以简单地生成一个404 not found或400错误的请求,因为有人试图发送数据而没有通过前端验证。 Note that this could cause issues if you need to do server side validation for some components (duplicate email addresses, usernames, etc). 请注意,如果您需要对某些组件(重复的电子邮件地址,用户名等)进行服务器端验证,则可能会导致问题。 In that case you can send the errors back in your desired format (JSON and XML are very common) and render them frontend. 在这种情况下,您可以将错误以所需的格式发送回(JSON和XML非常常见)并在前端呈现它们。

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

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