你如何将布尔值从PHP控制器传递给Ajax请求?

你如何将布尔值从PHP控制器传递给Ajax请求?

问题描述:

我用这个系统..取决于成功或错误,sendind一个成功= 0或1的JSON,这是正确的还是有更好的更正确的方法来传递true或false给Ajax调用?你如何将布尔值从PHP控制器传递给Ajax请求?

if (empty($item)) { 

       // add to the DB 

       $return['success'] = 0; 
       return Response()->json($return); 

      } else { 

       $return['success'] = 0; 
       $return['message'] = "Already in Collection"; 
       return Response()->json($return); 

      } 

然后在阿贾克斯:

jQuery(function ($) { 
    $(document).ready(function() {  
     $("body").on("submit", ".dynamic-form", function (e) {  
      var form = $(this); 
      var span = $(form).find('input[name="span_id"]').val();  
      $.ajax({ 
       url: form.prop('action'), 
       type: 'post', 
       dataType: 'json', 
       data: $(this).serialize(), 
       success: function (data) { 
         if (data.success == 1) { 

         alert("success"); 
        } 
        else if (data.success == 0) { 

         alert("error");  
        } 
       } 
      }); 
      e.preventDefault(); 
     }); 
    }); 
}); 

我用truefalse,然后比较像if (data.success)。 如果你想要一个布尔发送一个布尔值,但这只是我的看法。

这只取决于你,你可以或保存success为你做status ...

<?php 
if (empty($item)) { 
    // add to the DB 

    $return['success'] = true; 
} else { 

    $return['success'] = false; 
    $return['message'] = "Already in Collection"; 
} 

return Response()->json($return); 
+0

嗯,我在做这样的,但随后阿贾克斯认为一切真实。 – Chriz74

+0

@ Chriz74你有哪些警报是否成功或错误。你的数据解析为json? – VeeeneX