Null value in data obtained from JSON

3

I have a script that recovers the information of a JSON as I can put so that if it has nothing the JSON does not put anything in the variable items . This is my code:

<script type="text/javascript">
        $(function () {
            $("#IdPlantel").change(function () {
                $.getJSON("Oferta/List/" + $("#IdPlantel>option:selected").attr("value"), function (data) {
                    var items;
                    if (data == null) {// no lo respeta
                        items = "";
                    }
                    else {
                        $.each(data, function (i, state) {
                            items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                        });
                    }

                    $("#States").html(items);
                });
            });
        });
    </script>
    
asked by Alberto López Marroquín 21.12.2015 в 21:58
source

2 answers

2

I doubt that a server returns a null response. Most likely, the server sends an empty response. Therefore, try evaluating if data is an empty string. This is one way:

if (data === "") {
    //...
} else ...

Another way:

if (data.length === 0) {
    //...
} else ...

If you want to evaluate if data is null, use this evaluation:

if (data) {
    //...
} else ...
    
answered by 21.12.2015 / 22:01
source
2

You can check as follows with JavaScript pure.

if ( data.length == 0 ) {
     console.log("NO HAY DATOS!")
}

or you can also use jQuery , as follows:

if (jQuery.isEmptyObject(data))
{
    console.log("objeto Vacío");
}

I hope it works for you, regards.

    
answered by 21.12.2015 в 22:08