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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看