如何在Javascript中查询Dbpedia [英] how to query Dbpedia in Javascript
问题描述
我想用Javascript从Dbdepdia获得《土木工程英语》摘要。
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\
}";
这是我如何编码url以将其传递给ajaxx
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>
推荐答案
我使用另一种方法r多行字符串,我直接将其用于针对DBPedia的SPARQL查询编写。
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.
现在,一旦我需要运行查询,就对查询本身进行编码并将其附加到URL。
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.
我这样做:
var queryUrl = url+"?query="+ encodeURIComponent(query) +"&format=json";
这篇关于如何在Javascript中查询Dbpedia的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!