2013-10-18 239 views
1

我请从AJAX(addContent)一个PHP函数:停止执行脚本?

protected $output = array('success'=>0, 'message'=>'There was an error, please try again.'); 

public function addContent() 
{ 
    $imgName = $this->doSomething(); 
    $this->doSomethingElse(); 

    //save imageName to DB 
    $this->output['success'] = 1; 
    return $output; 
} 

private function doSomething() 
{ 
    if($imageOk){ 
     return $imageName; 
    } 
    else 
    { 
     $this->output['message'] = 'bad response'; 
     //how to return output? 
    } 

} 

我已经简单为了说明的目的的方法。

如果方法'doSomething()'的输出有错误的响应,我怎么能从addContent方法返回给ajax?如果输出错误,我想退出脚本并不继续执行doSomethingElse()。

+0

'退出()'会停止脚本 – George

+0

或者你可以用'死()' –

+0

_Or_你可以抛出一个异常,而不是抓住它,而是依靠注册的异常处理程序 –

回答

3

只是要doSomething返回false,如果验证失败,然后检查该条件:

public function addContent() 
{ 
    $imgName = $this->doSomething(); 
    if ($imgName === false) { 
     return "your error message"; 
    } 
    $this->doSomethingElse(); 

    //save imageName to DB 
    $this->output['success'] = 1; 
    return $output; 
} 

private function doSomething() 
{ 
    if($imageOk){ 
     return $imageName; 
    } 
    else 
    { 
     $this->output['message'] = 'bad response'; 
     return false; 
    } 
} 

你可以使用任何exitdie按照该意见,但这些都立即终止该脚本,因此,除非您在调用这些函数之前回应或将错误消息分配给模板,则不会返回错误消息。

1

的看到它解决(与抛除外):

protected $output = array('success'=>0, 'message'=>'There was an error, please try again.'); 

public function addContent() 
{ 
    try{ 
     $imgName = $this->doSomething(); 
     $this->doSomethingElse(); 

     //save imageName to DB 
     $this->output['success'] = 1; 
     return $this->output; 
    } 
    catch(Exception $e){ 
     $this->output['success'] = 0; 
     $this->output['message'] = $e->getMessage(); 
     return $this->output; 
    } 
} 

private function doSomething() 
{ 
    if($imageOk){ 
     return $imageName; 
    } 
    else 
    { 
     throw new Exception('bad response'); 
    } 

} 
0

你可以使用异常处理。

protected $output = array('success'=>0, 'message'=>'There was an error, please try again.'); 

public function addContent() 
{ 
    try { 
     $imgName = $this->doSomething(); 
    } catch (Exception $e) { 
     $this->output['message'] = $e->getMessage(); 
     return $this->output; 
    } 
    $this->doSomethingElse(); 

    //save imageName to DB 
    $this->output['success'] = 1; 
    return $output; 
} 

private function doSomething() 
{ 
    if($imageOk) { 
     return $imageName; 
    } 
    else { 
     throw new Exception('bad response'); 
    } 

} 
+0

@CreatoR拍我来吧。 – Magicode