我从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 :(得分: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;
}
}
您可以根据评论使用exit
或die
,但这些都会立即终止脚本,因此除非您在调用这些函数之前回显或将错误消息分配给模板,否则不会返回错误消息。
答案 1 :(得分: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'); } }
答案 2 :(得分: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');
}
}