【问题标题】:check if array it´s empty javascript检查数组是否为空javascript
【发布时间】:2022-01-25 05:14:58
【问题描述】:

我正在准备通过响应 ajax 和 laravel 后端创建函数来使用 jquery 验证我的表单。

在我的后端我有这个:

/**
     * SEARCH DATA CLIENT FOR CREATE PRECONTRATO
     */
    public function searchClient(Request $request)
    {
        $client = $request->get('documento');

        $clientSearch = Cliente::where('CIF_NIF', $client)->get();

        if($clientSearch->count() > 0){
            return $clientSearch[0];
        }
        
        return $clientSearch;
    }

如果查询不返回任何结果,此函数返回客户端或空集合。我的问题是我无法检查这种情况。

如果我输入了一个在我的数据库中不存在的数据,请返回:

[]
No properties

没关系,不存在,但我的 success function ajax 中有它,这是错误的

我在 ajax 中有这个:

$.ajax({
    url: "{{ route('admin.precontratos.searchClient') }}",
    method: "POST",
    data: { "tipo_documento": tipoDocumento, "documento": documento, 
        "_token": token,
    },
    success: function(response){
        if(response != null || response != "" || response.length > 0 ){
            console.log(response.length);
            $("#apellido1_titular").hide();
            $("#apellido2_titular").hide();
            $("#apellido1_titular_label").hide();
            $("#apellido2_titular_label").hide();
            $("#caducidad_dni").val(changeFormatDate(response.CAMPOCONFC6));
            $("#nombre_titular").val(response.NOMBREFISCAL);

            if(response.MOVIL != "" || response.MOVIL != null){
                $("#tipo_telefono").val('movil');
                $("#telefono1").val(response.MOVIL);
            }
            if(response.TELEFONOS != "" || response.TELEFONOS != null){
                $("#tipo_telefono2").val('fijo');
                $("#telefono2").val(response.TELEFONOS);
            }
            $("#email_titular").val(response.E_MAIL);
            
            let date_born = response.CAMPOCONFC5;
            
            $("#fecha_nacimiento").val(changeFormatDate(date_born));
            $("#pais_nacimiento").val(response.CAMPOCONFC3);
            $("#nacionalidad").val(response.CAMPOCONFC4);

            if(response.CAMPOCONFC2 == "UNION LIBRE"){
                $("#estado_civil").val('pareja_de_hecho_convivencia');
            }
            if(response.CAMPOCONFC1 == "FIJO/DISCONTINUO"){
                $("#tipo_ocupacion").val("PRIVATE_EMPLOYEE");
                $("#ocupacion").val("PERMANENT_SEASONAL");
            }

            $("#nombre_calle").val(response.DIRECCION);
            $("#iban_ccc").val(response.IBAN);

            /** VALIDATION INPUTS FILLED */
            validateInputsPrecontrato();
        }else{
            console.log("entro");
        }

但总是返回 console.log(response.length); 我需要我的函数转到 else 块并且永远不会进入那里。我不知道我做错了。

感谢帮助和自述文件

【问题讨论】:

  • 这个我看了好几遍了,最后一句的问题解释一点都不清楚
  • 如果要检查长度,则需要使用带有响应类型 JSON 的 Ajax,还需要从 PHP 函数返回 JSON。
  • 所以 console.log(response,response.length);看看实际的反应是什么
  • 试试这个:if(response != null && response != "" && response.length > 0 ){
  • 还有一件事,您使用的是 OR 条件而不是 AND 条件,请更正您的响应检查条件

标签: javascript php jquery ajax laravel


【解决方案1】:

您正在使用 XHR 请求到您的 Web 服务器。您必须以正确的格式接受响应,因为您的后端代码必须响应 JSON 格式的数据。

public function searchClient(Request $request) {

    $client = $request->get('documento');
    $clientSearch = Cliente::where('CIF_NIF', $client)->first();

    return $clientSearch 
    ? response()->json([
            'status' => 'success',
            'content' => $clientSearch
        ])
    : response()json([
            'status' => 'error',
            'content' => []
        ]);
}

在您的 Ajax 成功方法中,您可以检查将状态属性设置为成功的响应

success: function(response){
        if(response.hasOwnProperty('status') && response.status === 'success') {
            // Your code logic for success
        } else {
            // Your code logic for error
        }

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 2011-11-04
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2011-01-23
    相关资源
    最近更新 更多