dongyong3223
2014-05-06 14:18
浏览 73
已采纳

使用AJAX和JQuery使用PHP进行简单验证

I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script.
When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.

What is the best way to do that?

<html>
    <head>
    </head>
    <body>
        <form action="submitForm.php" action="POST">
            <input type="text" name="username" />
            <input type="password" name="password" />
            <input type="submit" name="submit" />
        </form>
    </body>
</html>

submitForm.php:

<?php
    echo $_POST["username"];
    echo "<br />";
    echo $_POST["password"];
?>

图片转代码服务由CSDN问答提供 功能建议

我是 AJAX 的新手,我想学习如何验证表单。 假设,我有一个带有两个输入字段的表单。 当我点击提交时,我想用PHP脚本检查页面。
当验证成功时,我想重定向到 action =“submitForm.php”。 当一个或多个字段根据 validation.php 无效时,我想留在页面上并在字段旁边显示错误消息。
\ n

最好的方法是什么?

 &lt; html&gt; 
&lt; head&gt; 
&lt; / head&gt; 
&lt; body&gt;  
&lt; form action =“submitForm.php”action =“POST”&gt; 
&lt; input type =“text”name =“username”/&gt; 
&lt; input type =“password”name =“ 密码“/&gt; 
&lt; input type =”submit“name =”submit“/&gt; 
&lt; / form&gt; 
&lt; / body&gt; 
&lt; / html&gt; 
  <  /pre>
nn 

submitForm.php:

nn
<?php
 echo $ _POST [“username”]; 
 echo“&lt; br  /&gt;“; 
 echo $ _POST [”password“]; 
?&gt; 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutang1873 2014-05-06 14:28
    已采纳

    In order to process the fields before actually submitting the form, you can catch its submit event:

    <form action="submitForm.php" action="post" onsubmit="return MyValidation()">
    

    Then, in your javascript:

    function MyValidation() {
        var valid = false;
    
        $.ajax({
            type: "POST",
            url: "validation.php",
            async: false,
            data: { name: $('#username').val(), password : $('#password').val() }
        })
        .done(function( data ) {
            if(data == 'true') {
                valid = true;
            }
        });         
    
        // not valid, return false and show some hidden message
        return valid;
    }
    

    (you need to add an ID to the <input> fields in order for the jquery selectors to work...)

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanjihe5180 2014-05-06 14:27
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题