how to query Dbpedia in Javascript

半城伤御伤魂 提交于 2020-01-23 09:54:53

问题


I want to get the Abtract of english article of civil engineering from Dbdepdia in Javascript. this is what I tried but it fail.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">

</style>
</head>
    <script type="text/javascript">
    var url = "http://dbpedia.org/sparql";
    var query = "\
     PREFIX dbpedia2: <http://dbpedia.org/resource/>\
     PREFIX Abs: <http://dbpedia.org/ontology/>\
    SELECT ?abstract\
   WHERE {\
            ?s dbpedia2:Civil_engineeringe\"@en;\ Abs:abstract ?abstract\ 
    }";

this how I encode the url to pass it to ajaxx

 var queryUrl = encodeURI( url+"?query="+query+"&format=json" );
    $.ajax({
        dataType: "jsonp",  
        url: queryUrl,
        success: function( _data ) {
            var results = _data.results.bindings;
            for ( var i in results ) {
                var res = results[i].abstract.value;
                alert(res);
            }
        }
    });
</script>
    <body></body>

</html>

回答1:


I use a different approach for multiline strings, and i use it directly for SPARQL query writing against DBPedia.

var query = [
 "PREFIX dbpedia2: <http://dbpedia.org/resource/>",
 "PREFIX Abs: <http://dbpedia.org/ontology/>",
 "SELECT ?abstract",
 "WHERE {",
    "?s dbpedia2:Civil_engineeringe\"@en;",
    "Abs:abstract ?abstract",
 "}"
].join(" ");

I do it this way because that allows me to adjust the line separator if encoding issues arise, and also it allows me to easily comment lines out if necessary.

Now, once i need to run the query, i encode the query itself and append that to the URL.

Be careful with how you are wrapping the entire query string, because it might be encoding the keys, values, and equals sign as escaped characters.

I do it this way:

var queryUrl = url+"?query="+ encodeURIComponent(query) +"&format=json";



回答2:


The encoding seems okay, but your original SPARQL / JavaScript does not look Okay to me.

var query = "\
 PREFIX dbpedia2: <http://dbpedia.org/resource/>\
 PREFIX Abs: <http://dbpedia.org/ontology/>\
 SELECT ?abstract\
 WHERE {\
         ?s dbpedia2:Civil_engineeringe\"@en;\ Abs:abstract ?abstract\ 
 }";

Does not result in a valid JavaScript string as there is a space after '?abstract\', meaning you're escaping a space character. Check out this question relating to multiline JavaScript strings: Creating multiline strings in JavaScript.

Moreover, the SPARQL query is plain wrong at the moment. Try to build it out and test it first here and take a look at the spec.



来源:https://stackoverflow.com/questions/22769701/how-to-query-dbpedia-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!