How to display alert box when no json value is giv

2020-08-04 10:18发布

问题:

I have displayed the result of a SPARQL query in a HTML page using Json, my question is when a certain value is entered and the query does not display a result it should display a alert box. My code is below:

HTML

  <table id="results">
     </table>

Query script

      var query = [
            "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",


  "PREFIX yago: <http://dbpedia.org/class/yago/>",
    "PREFIX type: <http://dbpedia.org/class/yago/>",
    "PREFIX prop: <http://dbpedia.org/property/>",
    "SELECT ?name ?runtime",
    "WHERE {",
    "?film rdf:type dbo:Film.",
    "?film dbp:name ?name.",
    "?film dbo:director dbr:Peter_Jackson.",
    "} GROUP BY ?name ?runtime"
            ].join(" ");
            alert("this query: [" + query + "]");
            var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
            console.log(queryUrl);
            $.ajax({
                dataType: "jsonp",
                url: queryUrl,
                success: function (data) {
                    console.log(data);
                    // get the table element
                    var table = $("#results");

                    // get the sparql variables from the 'head' of the data.
                    var headerVars = data.head.vars;

                    // using the vars, make some table headers and add them to the table;
                    var trHeaders = getTableHeaders(headerVars);
                    table.append(trHeaders);

                    // grab the actual results from the data.
                    var bindings = data.results.bindings;

                    // for each result, make a table row and add it to the table.
                    for (rowIdx in bindings) {
                        table.append(getTableRow(headerVars, bindings[rowIdx]));
                    }
                    if (bindings.trim().length == 0) {
                        alert("empty");   //IF BINDING IS EMPTY DISPLAY ALERT BOX
                    }


                }
            }); 

As for now it does not display anything if bindings is empty, it just shows trHeaders.

How can I make an alert box pop up if bindings is empty or if <td> is empty? Hope this question was understood. Thanks for your time.

回答1:

You can do this several different ways:

If bindings is a constant of your object, but may sometimes be empty:

if (data.results.bindings.length) {
    //exists
} else {
    alert('goes here');
}

If bindings is not always set in the response from the server:

if (data.results.hasOwnProperty('bindings')) {
   //exists
} else {
    alert('goes here');
}