如何从controller.action获取ajax响应true / false

时间:2012-10-19 11:07:59

标签: javascript php jquery ajax cakephp

我想检查客户端名称是否存在,然后不创建它 功能和每件事情都很完美。
我需要的是:函数返回true或false到我的ajax函数。

我在js和ajax中的创建函数是:

function createClient(){
       var newClientForm = $$('newClientForm').getValues();
       var client_name = newClientForm.client_name;

       if (client_name != ''){
       url_call = window.server_name + "/index.php/clients/create_new_client/"+client_name; 
       url_call = url_call.replace(/\n/g, '|');
       $.ajax({
              url: url_call ,               
              success: function(data) {
                       if ((data==true)||(data==false)){
                            alert('data true');
                        }


              }     
        }); 
        }else{            
            dhx.alert({title:'Error', message:"Please enter the client name."});
        }
    };

和我的控制器在cakephp中

function create_new_client($string = null){
            $this->layout = 'default_really_empty';
            $string = urldecode($string);
            $explode_item = explode('^', $string);

            $client_name        = $explode_item[0]; 

            //--Sreach if the Client is already there don't create it
            $modelClassChild = 'Client';
            $this->loadModel($modelClassChild);                
            $objects=$this->$modelClassChild->find('all',array('conditions'=>array($modelClassChild .'.deleted'=>'0', 
                                                                                   $modelClassChild .'.name'=>$client_name)));
            foreach($objects as $object) { 
                $dbName = $object['Client']['name'];
            }                

            if ($client_name != $dbName){  
            //--Sreach if the Client is already there don't create it
                $clientArray = array();
                $fields = array();

                $clientArray['Client']['name']  = $client_name;
                $fields[] = 'name';

                $client_exists = FALSE;                    

                $this->Client->create();
                $this->Client->save($clientArray, true); 
           }else{
               $client_exists = TRUE;                   
           }
           $this->set('client_exists',$client_exists);
    }

1 个答案:

答案 0 :(得分:0)

返回布尔值

if ($client_name != $dbName){  
    //--Sreach if the Client is already there don't create it
    $clientArray = array();
    $fields = array();

    $clientArray['Client']['name']  = $client_name;
    $fields[] = 'name';


    $this->Client->create();
    $this->Client->save($clientArray, true); 

    return false;                    

}else{
    return true;                   
}

检查ajax的成功回调为

success: function(data) {
    if ((data==0)||(data==1)){
        alert('data true');
    }
}