【问题标题】:How to display alert box when no json value is given没有给出json值时如何显示警告框
【发布时间】:2023-03-15 10:13:01
【问题描述】:

我已经使用 Json 在 HTML 页面中显示了 SPARQL 查询的结果,我的问题是当输入某个值并且查询不显示结果时,它应该显示一个警告框。我的代码如下:

HTML

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

查询脚本

      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
                    }


                }
            }); 

目前,如果bindings为空,它不会显示任何内容,它只显示trHeaders

如果bindings 为空或&lt;td&gt; 为空,如何弹出警告框? 希望这个问题能被理解。感谢您的宝贵时间。

【问题讨论】:

标签: javascript jquery json sparql


【解决方案1】:

您可以通过几种不同的方式做到这一点:

如果bindings 是您对象的常量,但有时可能为空:

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

如果bindings 并不总是在服务器的响应中设置:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多