Clean way to throw php exception through jquery/ajax and json

前端 未结 5 745
孤城傲影
孤城傲影 2020-12-04 18:02

Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.

5条回答
  •  暖寄归人
    2020-12-04 18:38

    If all the errors should be treated in the same way (showing a dialog for example). You can do it this way:

    PHP End:

    public function throwJsonException($msg) {
        echo json_encode(array('error'=> true, 'msg' => $msg));
    }
    
    throwJsonException('login invalid!');
    

    jQuery End:

    $(document).ajaxSuccess(function(evt, request, settings){
        var data=request.responseText;
        if (data.length>0) {
            var resp=$.parseJSON(data);
            if (resp.error)
            {
                showDialog(resp.msg);
                return;
            }                   
        }    
    });
    

提交回复
热议问题