2017-08-31 57 views
0

你好我想附加解析的json(我從xmlhttprequest獲得)到一個html文件。附加解析的json到html

這裏是我的代碼:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>alert solr response</title> 
<script src="https://code.jquery.com/jquery-3.2.1.js"> 
</script> 
<script> 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == XMLHttpRequest.DONE) { 
      var json = JSON.parse(xhr.responseText); 
      var data = json.facet_counts.facet_dates["dc.date.accessioned_dt"]; 
      delete data.gap; 
      delete data.end; 
      delete data.start; 
      console.log(data) 
      $("#test").append(data); //here is the problem, I could append xhr.Responsetext but this is not what I want 
     } 
    } 
    xhr.open('GET', 'http://localhost:8080/solr/search/select?indent=on&rows=0&facet=true&facet.date=dc.date.accessioned_dt&facet.date.start=2016-01-01T00:00:00Z&facet.date.end=2017-12-01T00:00:00Z&facet.date.gap=%2B1MONTH&q=search.resourcetype:2&wt=json&indent=true', true); 
    xhr.send(null); 
</script> 
</head> 
<body> 
<p id = "test">This is the json sample: <br></p> 
</body> 
</html> 

我知道有很多在那裏類似的問題和可能的重複,我很抱歉,我不能用他們對我的情況下(作爲一個小白和所有) 謝謝

+0

字符串化並不好看,是很難讀,我想在不同的行各個領域,如JSON –

+0

'JSON.stringify(OBJ,空,2);'[進入滿足神](https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) –

+0

只是一個提示,如果你使用jQuery,[$ .get()]( https://api.jquery.com/jquery.get/) – Endless

回答

0

如果你使用jQuery,當你得到你的數據到stringify這個內容使用第三個參數來獲得你想要的縮進時,你可以簡化這一點,因爲它只是純文本,你也必須將其附加到<pre>標記或將p標記處的css設置爲:white-space: pre

$.get('https://httpbin.org/get').then(function(data) { 
 
    delete data.gap; 
 
    delete data.end; 
 
    delete data.start; 
 

 
    $("#test").text(JSON.stringify(data, null, 2)); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<pre id="test"></pre>

+0

OP想分析,然後刪除一些json元素,你沒有解析你的jQuery代碼的一部分。 – Uttam

+0

事情是,你不需要解析部分因爲jquery會爲你做那個... – Endless