2016-11-01 3 views
-3

Когда я запрашиваю сервер, я получаю файл JSON в ответ. Файл JSON, который я верну, будет в следующем формате.Как использовать данные JSON?

{ 
    "head": { 
    "link": [], 
    "vars": ["bookName", "author"] 
    }, 
    "results": { 
    "distinct": false, 
    "ordered": true, 
    "bindings": [ 
     { 
     "bookName": { 
      "type": "literal", 
      "xml:lang": "en", 
      "value": "Of Mice and Men" 
     }, 
     "author": { 
      "type": "literal", 
      "xml:lang": "en", 
      "value": "John Steinbeck" 
     } 
     } 
    ] 
    } 
} 

Это то, что я сделал до сих пор:

$.ajax({ 
    dataType: "jsonp", 
    url: queryUrl, 
    success: function(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; 

     var book = data.results.bindings[1].bookName.value; 

     // for each result, make a table row and add it to the table. 
     var numberOfBooks = 0; 
     for(rowIdx in bindings){ 
      table.append(getTableRow(headerVars, bindings[rowIdx])); 
      numberOfBooks++; 
     }    

     document.getElementById("searched-for").innerHTML="<h1>You seach for " + '"' + input + '"' + " and we found " + numberOfBooks + " books </h1>"; 
    } 
});   

То, что я хочу, чтобы иметь возможность сделать что-то вроде этого:

var book = data.results.binding[1].bookName.value; 
+1

Массивы с нулевым индексированием, поэтому 'bindings [1]' выбирает элемент * second * (и есть только один). Это проблема? – JJJ

+1

Это не JSON, это объект javascript. вместо использования 'for in' пытайтесь использовать методы forEach или map. @JJJ прав, у вас есть единственный объект в массиве, поэтому он должен быть [0] вместо [1] –

ответ

1

Попробуйте это:

$.ajax({ 
dataType: "jsonp", 
url: queryUrl, 
success: function(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; 

    var book; 

    if(bindings && bindings.length) { 
     book = bindings[0].bookName.value; 
    } 

    // for each result, make a table row and add it to the table. 
    var numberOfBooks = 0; 
    for(rowIdx in bindings){ 
     table.append(getTableRow(headerVars, bindings[rowIdx])); 
     numberOfBooks++; 
    }    

    document.getElementById("searched-for").innerHTML="<h1>You seach for " + '"' + input + '"' + " and we found " + numberOfBooks + " books </h1>"; 
} 
}); 

Но это будет только первая книга, i существует.

Смежные вопросы