douhui3330 2010-07-28 15:55
浏览 40
已采纳

将未通过PHP验证的字段返回给jQuery

I'm using jQuery with PHP for form validation. I want to return the fields that do not validate so i can highlight them using javascript

this is my attempt using PHP(validate.php):

<?php
...
$a_invalidInput = array();

$from = $_POST['from'];
$to = $_POST['to'];
$email_to = $_POST['email_to'];

if( empty($from) ){
   $a_invalidInput[] = 'from';
}

if( empty($to) ){
   $a_invalidInput[] = 'to';
}

//validate the email_to address
if( empty($email_to) ){
   $a_invalidInput[] = 'email_to';
} else{

   //do more validation for email
}
...
?>

This is my jquery code:

...

var data = "from="+ from + "&to=" + to + "&email_to=" + email_to; 

$.ajax({
   url: "includes/validate.php",
   type: "POST",
   data: data,
   success: function(){

      //highlight fields that do not pass validation

   }
});

...

I'm not sure if i'm on the right path or not AND how to return the input fields that do not pass validation so i can add a class to highlight the fields that do not pass validation.

I could do this using javascript but i prefer using a php file for validation

Thanks Marco

展开全部

  • 写回答

2条回答 默认 最新

  • doushuo1080 2010-07-28 18:59
    关注

    One way to go would be to return a json encoded array of fields that do not pass.

    From your PHP script, output your Invalid Input array (json encoded so your javascript can use it). Then on the Javascript side, you want to check if that output has any values. If it does, use them.

    <?php
        // at the end of your script
        header('Content-type: application/json');
        echo json_encode($a_invalidInput);
        exit();
    ?>
    

    Now in your JQuery, you want to use that json output...

    $.ajax({
        url: "includes/validate.php",
        type: "POST",
        dataType: "json",
        data: data,
        success: function(data){
            if (data !== undefined
            &&  data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var field_name = data[i];
                    var field = $('input[name=' + field_name + ']');
    
                    // now you have the field, so you can modify it accordingly.
                }
            }
        }
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 KeiI中头文件找不到怎么解决
  • ¥15 QT6将音频采样数据转PCM
  • ¥15 本地安装org.Hs.eg.dby一直这样的图片报错如何解决?
  • ¥15 下面三个文件分别是OFDM波形的数据,我的思路公式和我写的成像算法代码,有没有人能帮我改一改,如何解决?
  • ¥15 Ubuntu打开gazebo模型调不出来,如何解决?
  • ¥100 有chang请一位会arm和dsp的朋友解读一个工程
  • ¥50 求代做一个阿里云百炼的小实验
  • ¥15 查询优化:A表100000行,B表2000 行,内存页大小只有20页,运行时3页,设计两个表等值连接的最简单的算法
  • ¥15 led数码显示控制(标签-流程图)
  • ¥20 为什么在复位后出现错误帧