javascript
  • html
  • web
  • sparql
  • 2015-09-12 209 views 1 likes 
    1

    我試圖在html中進行sparql查詢。我有這樣的代碼:顯示sparql查詢結果的問題

    <script type="text/javascript"> 
         document.write("<strong>Hola!</strong>"); 
         var SPARQL_ENDPOINT = 'http://datos.zaragoza.es/sparql'; 
         var query = 'PREFIX pproc: <http://contsem.unizar.es/def/sector-publico/pproc#>\ 
         PREFIX dcterms: <http://purl.org/dc/terms/>\ 
         SELECT DISTINCT ?uri ?titulo ?servicioGestor WHERE {\ 
         ?uri a <http://contsem.unizar.es/def/sector-publico/pproc#Contract>;\ 
         dcterms:title ?titulo;\ 
         pproc:managingDepartment ?managingDepartment.\ 
         ?managingDepartment dcterms:title ?servicioGestor} ORDER BY ?titulo'; 
    

    現在我必須去完成它,所以我可以看到查詢的結果時,我在瀏覽器中打開該文件。

    回答

    1

    您需要:

    使用該端點和查詢爲查詢構建完整的URL。您可能想要以JSON格式請求結果,因爲這會使結果更容易處理。查詢和格式需要以URL編碼。例如:

    var url = SPARQL_ENDPOINT 
        + '?query=' + encodeURIComponent(query) 
        + '&format=' + encodeURIComponent('application/sparql-results+json'); 
    

    對該URL發出GET請求 - 大量代碼可用於此在線可用。

    然後,您可以解析並顯示返回的JSON結果,例如,爲表:

    function printTable(response){ 
        var results = JSON.parse(response); 
        var table = '<table>'; 
        results.results.bindings.forEach(function (result){ 
         table += '<tr><td>' + result.uri.value + '</td><td>' + result.titulo.value 
          + '</td><td>' + result.servicioGestor.value + '</td></tr>'; 
        }) 
        table += '</table>'; 
        document.write(table); 
    } 
    

    添加在console.log(results);以查看瀏覽器的Javascript控制檯窗口中的整個結果,並弄清楚到底要顯示的內容。

    相關問題