检查JSON内容是否为NULL

时间:2014-09-04 19:04:16

标签: jquery json zend-framework2

使用$ .post ....接收JSON数据,并且我尝试在它为空时添加if语句。看下面的链接:

但在谷歌浏览器中出现错误,如未捕获的TypeError:undefined不是函数

详细问题

我使用Zend Framework并且在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;
        }
    }
}

此Action getError消息在script.js中我回显它们以进行查看。

....

    $.post(url,data,function(resp)
    {
        if (typeof resp === "object") {
            $('#'+id).parent().find('.alert-danger').remove();
            $('#'+id).parent().append(getErrorHtml(resp[id], id));
            console.log(typeof resp);
          } else {
            $("#formLoginErrorMessage").addClass("alert-danger");
            $("#formLoginErrorMessage").append("<li>" + resp + "</li>");
            console.log(typeof resp);
          }
    },'json');
....

resp 包含错误消息。我想检查resp是否为null然后添加如下内容:

if(resp isNull)
{
    ('#loginForm').submit(function(){
     return true;
    });
 } else {
    ('#loginForm').submit(function(){
     return false;
    });
     $.post(......
 }

希望这会清楚一点。

500错误如果Chrome Developer Tools中没有错误消息,则显示错误:

  

POST http://new.local/register/ajax/ 500(内部服务器错误)jquery-1.8.2.min.js:2

     

发送jquery-1.8.2.min.js:2

     

p.extend.ajax jquery-1.8.2.min.js:2

     

p。(匿名函数)jquery-1.8.2.min.js:2

     

doValidation script.js:26

     

(匿名函数)script.js:9

     

p.event.dispatch jquery-1.8.2.min.js:2

     

g.handle.h

1 个答案:

答案 0 :(得分:0)

$.getJSON期望响应是有效的JSON。如果它可能为空,则表示无效,因此您无法使用此功能。您应该使用$.get()并在检查到响应不为空后调用$.parseJSON()

$.get(URL, function(json) {
    if (json != '') {
        data = $.parseJSON(json);
    } else {
        // do something else
    }
});