繁体   English   中英

使用AJAX / JSON进行PHP验证

[英]PHP Validation using AJAX / JSON

我的验证位于以json编码的php脚本中,我不确定如何在我的主要JavaScript函数中实现它。 我在我的php脚本中使用正则表达式来验证表单条件,我需要将其传递给JavaScript文件并为每个表单ID返回成功消息。
这是我到目前为止所拥有的。

 $(document).ready(function() { $("#submit").click(function() { // Clear any success or error messages $("#success").html(""); $("#errors").empty(); //make an AJAX call here, and set error or success accordingly $.post('backend.php',{act:'validate'}, function(getData) { //unsure about this function } }); // prevents submit button default behavior return false; }); }); 
 <html> <head> </head> <body> <h1>Form Validation</h1> <form id="PersonForm"> Name: <input id="name" type ="text" name="name"></input> <br><br> Postal Code: <input id="postal" type ="text" name="postal"></input> <br><br> Phone Number: <input id="phone" type ="text" name="phone"></input> <br><br> Address: <input id="address" type ="text" name="address"></input> <br><br> <input type="submit"></input> </form> <div id= "content"></div> <a href="frontend.html">Refresh</a> <a id="InsertDefault" href="#">Insert Default Data</a> <br><br> <p id='msg'></p> <ul id="errors"></ul> <p id="success"></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="main.js" type="text/javascript"></script> </body> </html> 

<?php
if ($_REQUEST['act'] == 'validate')
{
  $validateData = array();
  if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
  else $validateData['name'] = 0;

  if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
  else $validateData['phone'] = 0;

  if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/", $_REQUEST['postal'])) $validateData['postal'] = 1;
  else $validateData['postal'] = 0;

  if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/", $_REQUEST['address'])) $validateData['address'] = 1;
  else $validateData['address'] = 0;

  echo json_encode($validateData);
}
else echo "Should not happen";
?>

好吧,这将更适合于这样的实际ajax调用设置(未测试)

// Set values
var values = {};
values.act = "validate";
values.name = $('[name="name"]').val();
values.phone = $('[name="phone"]').val();
values.postal= $('[name="postal"]').val();
values.address= $('[name="address"]').val();

$.ajax({
    type: 'POST',
    url:'backend.php',
    data: values,
    dataType: 'JSON',
    success: 
    function(result)
    {
        // Here you can access the json object like this and
        // do whatever you like with it
        console.log(result.name);
        console.log(result.phone);
        console.log(result.postal);
        console.log(result.address);    
    }
});

我不确定您要寻找什么,但这对您有用吗? 基本上,我们对对象进行字符串化(请参阅我对parseJSON的评论)并查找任何0,如果没有,则提交表单。 如果有0,我们将遍历每个键/值对并将错误推入数组,然后对每个错误进行处理,例如将它们放在错误区域中。 那对你有用吗?

var getData = {
    name:1,
    phone:1,
    postal:0,
    address:1
}
//if your info isn't looking like this, you may need to look in to $.parseJSON here http://api.jquery.com/jquery.parsejson/

if (JSON.stringify(getData).indexOf('0') == -1) {
    alert('all good!');
    //$('#PersonForm').submit();
}
else {
    var errorArr = [];
    $.each(getData, function(k, v) {
        if (v == 0) {
            errorArr.push('theres a problem with '+k);
        }
    });
    for (var i = 0; i < errorArr.length; i++) {
        alert(errorArr[i]);
    };
}

祝好运!

暂无
暂无

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

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