我使用維基API搜索的東西,我得到JSON其中有我想在query.search像這樣從迭代JSON數組元素創建JS的HTML表格行對象
0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and", …}
1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live", …}
2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and", …}
...
的數據,我需要的價值通過它與
for (var i = 0; i < data.query.search.length; i++) {
var result = data.query.search[i];
var title = result.title;
console.log(title); }
現在我想創建一個表,並把每個標題值在不同的行標題所以對於循環迭代的,我用這個代碼,但它不工作
var table = document.getElementById("resultTable");
var row = table.insertRow(i);
var cell1 = row.insertCell(i);
cell1.innerHTML = data.query.search[i].title;
在HTML部分我有
<div>
<table id="resultTable"></table>
</div>
我必須把創建表的代碼放到一個單獨的for循環或使用[i]
是錯誤的?
這裏是整個代碼:
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var format = "&format=json";
var request_url = "? action=query&format=json&prop=info&inprop=url&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#gosearch").click(function(e) {
e.preventDefault();
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data.query.search);
for (var i = 0; i < data.query.search.length; i++) {
var result = data.query.search[i];
var title = result.title;
console.log(title);
function drawTableHor(data) {
var table1 = document.getElementById("resultTable1");
for (var i = 0; i < data.query.search.length; i++) {
var row = table1.insertRow();
for(var prop in data.query.search[i]) {
if(prop !== 'title') continue;
var cell = row.insertCell();
cell.innerHTML = data.query.search[i][prop];
}
}
};
drawTableHor(data);
}
這一切都取決於你如何定義的JavaScript。你是否打算用JavaScript創建所有關聯的標籤,或者是否要迭代術語表?我的意思是,這種方法有很多種方法。我通常可能模板化,但我更喜歡把所有可能的東西放在JavaScript中,這使模糊MVC設計線 – Fallenreaper