来自AJAX请求的CodeIgniter中的表单验证失败

时间:2018-09-06 07:20:47

标签: php jquery ajax codeigniter serialization

我的PHP和jQuery代码发生错误,如下所示:

jQuery:

restore_command = 'cp /archive/%f %p'
recovery_target_time = '2018-09-07 03:25:46'


2018-09-07 03:35:57.745 EDT [8264] LOG:  database system was interrupted; last known up at 2018-09-07 03:23:31 EDT
2018-09-07 03:35:59.593 EDT [8264] LOG:  starting point-in-time recovery to 2018-09-07 03:25:46-04
2018-09-07 03:35:59.682 EDT [8264] LOG:  restored log file "000000010000000000000003" from archive
2018-09-07 03:35:59.722 EDT [8264] LOG:  redo starts at 0/3000028
2018-09-07 03:35:59.725 EDT [8264] LOG:  consistent recovery state reached at 0/3000130
2018-09-07 03:35:59.725 EDT [8262] LOG:  database system is ready to accept read only connections
2018-09-07 03:36:00.058 EDT [8264] LOG:  restored log file "000000010000000000000004" from archive
2018-09-07 03:36:00.097 EDT [8264] LOG:  recovery stopping before commit of transaction 562, time 2018-09-07 03:26:17.435255-04
2018-09-07 03:36:00.097 EDT [8264] LOG:  recovery has paused
2018-09-07 03:36:00.097 EDT [8264] HINT:  Execute pg_wal_replay_resume() to continue.
2018-09-07 03:36:54.138 EDT [8288] ERROR:  cannot execute CREATE TABLE in a read-only transaction
2018-09-07 03:36:54.138 EDT [8288] STATEMENT:  CREATE TABLE scale_data5 ( section NUMERIC NOT NULL, id1 NUMERIC NOT NULL, id2 NUMERIC NOT NULL );

HTML表单:

$('#form').submit(function(e){
    e.preventDefault();
    var me = $(this);
    var data = me.serialize();
    $.ajax({
        method :'POST',
        url:me.attr('action'),
        data:{data},
        dataType:'json',
        async:false,
        success:function(data){
            alert(data.success);
            if(data.success == true){
                alert('true');
            }
            else{
                alert('false');
            }
        }
    });
});

PHP控制器:

    <?= form_open('practice/check', array('id'=>'form'))?>
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit" name="button" id="submit">click</button>
    <?= form_close();?>

当jquery代码中发生警报事件时,即使字段被填满,也会始终返回false。.请帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

您需要更改

data: { data }

data: data

在您的AJAX代码中。

您的版本正在做的是将数据包装在一个额外的对象中。这样会导致一个名为“数据”的变量被提交到请求正文中的服务器,如下所示:

data=username%3Duser123%26password%3Dabcdef

这实际上是您想要的:

username=user123&password=abcdef

因此,PHP无法识别您正在发送的值。它只能看到一个名为“ data”的变量,就其而言,它包含一个随机字符串。它需要能够分别看到“用户名”和“密码”变量。

如果您在打开网络工具的情况下查看此JSFiddle http://jsfiddle.net/jcx2Ly5e/3/,请提交表单,并注意对“ test.php”的两个请求。第一个是不正确的,第二个是正确的。查看每个请求的正文以了解它们之间的区别。

P.S。您会注意到,这与JSON无关。您的PHP返回JSON,但是表单数据以标准的表单URL编码格式提交。 JSON不是问题的一部分,因此我编辑了您的问题以将其删除。