我正在尝试使用 Firefox 在 dbpedia 上执行异步 Ajax sparql 查询,但得到了一个奇怪的结果,并且无法找出错误。这一切似乎都有效(实际上在 Chrome、Edge 和 Internet Explorer 中都有效),但如果在 Firefox 中执行,则页面在执行查询后会无限期地继续加载,如果您刷新页面,它会显示一个空白页面。有人可以解释一下为什么会发生这种情况吗? 我什至尝试使用 jQuery 但结果相同。
<script>
//async request to the url -> print the result
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//query worked
document.write(xmlHttp.responseText);
//xmlHttp.abort();
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
//sparql query
var query = [
"PREFIX dbo: <http://dbpedia.org/ontology/>",
"SELECT ?album ?artist WHERE {",
"?album dbo:artist ?artist .",
"} LIMIT 10"
].join(" ");
//url for the query
var url = "http://dbpedia.org/sparql";
var queryUrl = url + "?query=" + encodeURIComponent(query);
//query call
httpGetAsync(queryUrl);
</script>
使用 jQuery:
<script>
//async request to the url -> print the result
function httpGetAsync(theUrl) {
$.ajax({
url: theUrl,
data: {
format: 'json'
},
error: function() {
document.write("error");
},
dataType: 'json',
success: function(data) {
document.write(JSON.stringify(data));
},
type: 'GET'
});
}
//sparql query
var query = [
"PREFIX dbo: <http://dbpedia.org/ontology/>",
"SELECT ?album ?artist WHERE {",
"?album dbo:artist ?artist .",
"} LIMIT 10"
].join(" ");
//url for the query
var url = "http://dbpedia.org/sparql";
var queryUrl = url + "?query=" + encodeURIComponent(query);
//query call
httpGetAsync(queryUrl);
</script>
最佳答案
编辑 dom 的元素而不是直接写入文档解决了问题。
document.getElementById('element').innerHTML = xmlHttp.responseText;
关于javascript - 在 Firefox 中执行 Ajax SPARQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162288/