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()。

4

3 回答 3

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根据注释使用,但它们都会立即终止脚本,因此除非您在调用这些函数之前回显或将错误消息分配给模板,否则不会返回您的错误消息。

于 2013-10-18T12:58:23.513 回答
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');
    }

}
于 2013-10-18T13:06:17.127 回答
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');
    }

}
于 2013-10-18T13:10:34.197 回答