使用jQuery访问数据状态

时间:2013-09-09 12:42:24

标签: jquery ajax

我正在使用以下内容设置一个简单的AJAX调用:

            if(validateEmail(email_val)){

                $.post($('#form_url').val(), { email: email_val }, function(data) { 
                    console.log(data);
                 } );

            }

一切正常,但我如何访问“状态”:是吗?

我想这样做:

if(status is true){ call this function }

if (array_key_exists('email', $_POST)) {                
            $this->form_validation->set_rules(array(
                                            array(
                                                 'field'   => 'email',
                                                 'label'   => 'Email',
                                                 'rules'   => 'trim|required|xss_clean|valid_email'
                                              ),
                                            )
                                        );

            if($this->form_validation->run() === FALSE) {
                $data = array('status' => FALSE, 'error' => $this->form_validation->error_array());
            }
            else {
                if($this->pages->addEntry()==true){
                    $data = array('status' => TRUE, 'error' => FALSE);
                } else {
                    $data = array('status' => FALSE, 'error' => 'You already participate in the competition');                
                }
            }
            echo json_encode($data); 
        } else {
            $dupe = false;
            if(is_numeric($id)) {
                $this->page = $this->pages->getSingleById($id, array('timestamps' => 2, 'files' => 5, 'longtexts' => 2, 'varchars' => 3));
                $this->page["timeLeft"] = $this->pages->countLeftTime($this->page["timestamps_1"]);
            } else {
                $this->page = $this->pages->getCurrentCompetition();
            }

            $this->view_vars = array(
                'page'  => $this->page,
                'dupe'  => $dupe,
                'signed_request'    => $_REQUEST['signed_request'],
            );

            return $this->load->view('html/pages/index', $this->view_vars);
        }

3 个答案:

答案 0 :(得分:1)

$.post($('#form_url').val(), { email: email_val },function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });

数据 - 包含来自请求的结果数据

status - 包含请求的状态(“success”,“notmodified”,“error”,“timeout”或“parsererror”)

如果您想在服务器端返回代码执行状态,则返回数据中的值,如'success'或true,或1或0,并在客户端比较相同的值。

答案 1 :(得分:0)

var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  $("#log").html( msg );
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

request.always(function(){
 alert('Ajax complete');
});

参考:http://api.jquery.com/jQuery.ajax/

在.done回调中,您应该查询服务器返回的对象并检查您想要的值。

if (msg.status == "something") {
   //do stuff
}

答案 2 :(得分:0)

如果您的状态在您收到的数据中,那么您可以执行“data.status”。你不需要任何进一步的东西。