dongxian1699 2013-04-01 18:16
浏览 48

与Jquery一起使用CodeIgniter登录表单

I am working with CodeIgniter and am trying to capture the JSON values that are returned from a controller using jquery $.ajax() function. Here is my "login/process" Controller below

        public function process() {
            $this->form_validation->set_rules('email','Email Address','trim|required|xss_clean'); 
            $this->form_validation->set_rules('passwd','Password','trim|required|xss_clean|md5|callback_check_database');

            $red = ($this->input->post('redirect_url')) ? $this->input->post('redirect_url') : null;
            if ($this->form_validation->run() == false) {
                $output = '{ "success": "no", "redirct": "' . $red . '", "err" : "' .validation_errors() . '" }' ;
            } else {
                //Go to private area
                $output = '{ "success": "yes", "redirct": "account" , "err" : ""}';
            }
        }

        header('Content-Type: application/json', true);
        echo json_encode($output);
    }
}

Here is part of my view below:

<script type='text/javascript' language='javascript'>
    $(document).ready(function() {
        $("#LoginForm").on("submit",function() {
            var datastring = 'email='+$("#email").val()+'&passwd='+$("#passwd").val()+'&redirect_url='+$("#redirect_url").val();
            $.ajax({
                type: "POST",
                url: "<?= base_url("login/process") ?>",
                dataType: "json",
                data: datastring,
                cache: false,
                success: function(output) {
                    //  alert(output.success);
                    if (output.success == 'yes') {
                        document.location.href=output.redirct
                    }
                    if (output.success == 'no') {
                        alert(output.err)
                    }
                }
                })
            return false;  // To prevent form submission
            })
    });
</script>

When I tried to debug with FireBug, below is what I got as the POST Response

"{ \"success\": \"no\", \"redirct\": \"messaging.php\", \"err\" : \"<p>The Password field is required.<\/p>
\" }"
  • 写回答

1条回答 默认 最新

  • drelgkxl93433 2013-04-01 18:21
    关注

    You can't use json_encode on a json string. It's for encoding arrays as a json string . I would suggest you to define $output as an array and then use json_encode (it's also less error-prone):

    $output = array("success" => "no", "redirect" => $red, "err" => validation_errors());
    
    echo json_encode($output);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘