如何通过Ajax获取两个或更多json_encode php echos?

时间:2017-11-17 13:09:43

标签: php arrays json ajax

   $errMsgUsername="";
    $errMsgPassword="";

    if ($_POST['username']==""){
     $errMsgUsername="Username is null";
    }
    if ($_POST['password']==""){
     $errMsgPassword="Password is null";
    }

    echo json_encode(['errMsgUsername'=>$errMsgUsername,'errMsgPassword',=>$errMsgPassword]); // json response 1

$success = "";
if ($_POST['username']!="" && $_POST['password']!=""){
$success = "Form data available";
json_encode(['success'=>$success]); // json response 2
}
$.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              dataType:"json",
              contentType: false,
              processData: false,
              success: function(response){
                //if fields null, the response has to display here.
                $('.div_username').html(response.errMsgUsername);
                $('.div_password').html(response.errMsgPassword);

                //if fields are not null the response has to display here/
                $('.div').html(response.success);

              }
            });

问题是当我提交表单时(用户名和密码为空),ajax响应按预期显示在Div中。但是当我提交表单时(用户名和密码对数据不为空),ajax响应不会显示在$('。div')。html(response.success);中。 当我看到在开发人员工具下检查ajax请求时,它显示请求成功,并且响应也像这样返回{“errMsgUsername”:“”,“errMsgPassword”:“”} {“成功”:“表单数据可用的“}。

所以这里的问题是ajax响应有两个两个 json_encode响应。那么如何成功管理这两个响应呢?

1 个答案:

答案 0 :(得分:0)

在Jomy回复你之前开始这个回复,发布它,因为我稍微清理了你的代码,可能会有用。

<?php

  $errors = array();

  if (empty($_POST['username'])){
   $errors['errMsgUsername']="Username is null";
  }
  if (empty($_POST['password'])){
   $errors['errMsgPassword']="Password is null";
  }

  if( !empty( $errors ) )
    return json_encode( $errors );

  // If failed, which means we succeeded.
  $success = array(
    'success' => 'Form data available'
  );

  return json_encode($success);