当没有任何Zend Json对象控制台抛出500错误

时间:2014-09-05 06:56:26

标签: php ajax json zend-framework2

我正在使用来自 LoginController.php 的操作:

public function ajaxAction()
{
    $form = $this->getServiceLocator()->get('LoginForm');
    $post = $this->request->getPost();
    $form->setData($post);
    $response   = $this->getResponse();

    if (!$form->isValid()){
        // something is invalid; print the reasons
        $json= $form->getMessages();
        $response->setContent(\Zend\Json\Json::encode($json));
        return $response;
    } else {
        $this->getAuthService()->getAdapter()->setIdentity(
            $this->request->getPost('email'))->setCredential(
            $this->request->getPost('password'));
        $result = $this->getAuthService()->authenticate();
        switch ($result->getCode()) {
            case Result::FAILURE_IDENTITY_NOT_FOUND:
            $json = "Email or password is incorrect";
            $response->setContent(\Zend\Json\Json::encode($json));
            return $response;
            case Result::FAILURE_CREDENTIAL_INVALID:
            $json = "Email or password is incorrect";
            $response->setContent(\Zend\Json\Json::encode($json));
            return $response;
        }
    }
}

我在 script.js 中获得了这些编码$json值:

$('#navLogin').removeAttr('style');
$('#labelLogin').css('display', 'none');

$("#Login input").blur(function()
{
    $("#formLoginErrorMessage").children().remove();
    var formElementId = $(this).parent().find('input').attr('id');
    doValidation(formElementId);
});

function doValidation(id, url)
{
    var url = 'ajax/';
    var data = {};
    $('input').each(function()
    {
        data[$(this).attr('name')] = $(this).val(); 
    });
    $.post(url,data,function(resp)
    {
        $('#'+id).parent().find('.alert-danger').remove();
        if(resp === null)
        {
            console.log("Dang");
        }else if (typeof resp === "object") {
            $('#'+id).parent().find('.alert-danger').remove();
            $('#'+id).parent().append(getErrorHtml(resp[id], id));
            console.log(resp);
          } else {
            $("#formLoginErrorMessage").addClass("alert-danger");
            $("#formLoginErrorMessage").append("<li>" + resp + "</li>");
            console.log(resp);
          }
    },'json');
}

function getErrorHtml(formErrors, id)
{
    var o = '<ul id="errors-'+id+'" class="alert-danger">';
    for(errorKey in formErrors)
    {
        o += '<li>' + formErrors[errorKey] + '</li>';
    }

    o+= '</ul>';
    return o;
}

使用 ajaxAction 我编码可能出现的登录表单中的错误消息并在$.post(url,data,function(resp){ ...中传递它们,其中 resp 是来自php的编码对象

问题如果在Google Developer Tools中无法编码,我会得到:

  

POST http://new.local/login/ajax/ 500(内部服务器错误)

修复通过将此添加到LoginController.php,我没有得到500错误并且可以处理JSON对象。

if(!isset($json)){
        $json = " ";
        $response->setContent(\Zend\Json\Json::encode($json));
        return $response;
    }
}

0 个答案:

没有答案