没有退出函数PHP不返回值

时间:2016-08-31 13:20:18

标签: php ajax codeigniter codeigniter-3

我需要帮助。我从Codeigniter返回值时遇到问题。每当我在exit;之后使用echo它工作正常,但无论何时我尝试return true,它都会工作。

PHP代码中的评论代码相同。如果我在exit之后使用echo它有效,但如果我不这样做则不会返回任何内容

Ajax请求

$('#social-form').on('submit', function(e){

    e.preventDefault();
    var str = $( "#social-form" ).serialize();
    if (str === '') {
        swal("Please Fill All Fields");
    } else {
        $.ajax({
            type: "POST",
            url: baseUrl + "/admin/social/",
            data: str
        })
        .done(function (data) {
                console.log(data);
                swal("Information", data, "info");
            })
        .error(function () {
            swal("Oops", "We couldn't connect to the server!", "error");
        });
    }
});

笨-3

public function social(){
    $name = $this->input->post('name');
    $profile = $this->input->post('profile');
    $this->form_validation->set_rules('name', 'name', 'required|trim');
    $this->form_validation->set_rules('profile', 'profile', 'required|trim');
    if ($this->input->post() && $this->form_validation->run() != FALSE) {
        $this->load->model('Social_model','social');
        $this->social->update($name,$profile);
        echo 1;
        //exit;
        //return true;
    }
    else
    {
        echo 0;
        //exit;
        //return false;
    }
}

2 个答案:

答案 0 :(得分:1)

CodeIgniter有一个布局,因此在输出响应后,可能会有响应后输出的视图,例如页脚或调试栏。

尝试使用控制台查看响应的状态代码。还要注意,在AJI调用之后,CodeIgniter退出并不是很糟糕,所以也许你应该只编写一个AJAX响应助手来完成所有这些操作(比如设置标题并添加exit)。

答案 1 :(得分:1)

您可能需要更具体地了解您的回音。这是几种可能的解决方案之一。

控制器

 public function social(){
    $name = $this->input->post('name');
    $profile = $this->input->post('profile');
    $this->form_validation->set_rules('name', 'name', 'required|trim');
    $this->form_validation->set_rules('profile', 'profile', 'required|trim');
    if ($name && $this->form_validation->run() != FALSE) {
        $this->load->model('Social_model','social');
        $this->social->update($name,$profile);
        $out = json_encode(array('result' => 'success'));
    }
    else
    {
        $out = json_encode(array('result' => 'failed'));
    }
        echo $out;
}

的javascript

$('#social-form').on('submit', function (e) {
    e.preventDefault();
    var str = $("#social-form").serialize();
    if (str === '') {
        swal("Please Fill All Fields");
    } else {
        $.ajax({
            type: "POST",
            url: baseUrl + "/admin/social/",
            data: str,
            dataType: 'json'
        })
          .done(function (data) {
              console.log(data);
              if (data.result === 'success') {
                  swal("Information", "Success", "info");
              } else {
                  swal("Information", "Failed", "info");
              }
          })
          .error(function () {
              swal("Oops", "We couldn't connect to the server!", "error");
          });
    }
});
相关问题