0

我正在使用 CodeIgniter 并尝试使用 jquery$.ajax()函数捕获从控制器返回的 JSON 值。这是我下面的“登录/进程”控制器

        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);
    }
}

以下是我的部分观点:

<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>

当我尝试使用 FireBug 进行调试时,以下是我得到的 POST 响应

"{ \"success\": \"no\", \"redirct\": \"messaging.php\", \"err\" : \"<p>The Password field is required.<\/p>\n\" }"
4

1 回答 1

1

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);
于 2013-04-01T18:21:16.960 回答