2014-12-04 45 views
0

我想追加一個json對象到頁面。我通過ajax獲得成功,但沒有顯示出來。Ajax json響應沒有附加到頁面

<form onsubmit="return false;"> 
{% csrf_token %} 
    Search:<input type="text" name="artist" id="artist" /> 
    <button class="updateButton" onclick="createlist()">submit</button> 
</form> 

function createlist(){ 
$.ajax({ 
    type: "POST", 
    url: "/rest/", 
    dataType: "json", 
    data: { 
     artist: $('#artist').val() 
    }, 
    headers: { 
     'X-CSRFTOKEN': "{{ csrf_token }}", 
    }, 
    success: function(data){ 
     $('#output').html(data); //also tried data.content 
    } 
}); 
} 

當我在devtools中查看響應和預覽時,響應似乎位於一個長轉義字符串中。

"[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/galloping-rider-and-other-figures.jpg\", \"title\": \"Galloping Rider and other figures\"}, \"model\": \"serve.art\", \"pk\": 63057} 

我該如何將它轉換成可用的東西?

回答

1
+0

仍然不是數據附加到頁面,當我做到這一點。 '$('#output')。html(JSON.parse(data));'不顯示。 – 2014-12-04 03:38:08

+1

抱歉可能會誤解您的問題。設置一個斷點,看看$('#output')是否得到元素 – Ryo 2014-12-04 03:48:29

+0

它現在正在工作,但我什麼也沒有改變,我所做的只是設置了一個斷點並逐步完成了devtools中的函數。這很奇怪,我想知道是什麼修復了它。 – 2014-12-04 04:04:49

1

不,你不能一個對象追加到HTML元素。

不要解析JSON,只是追加格式()如你得到。

我已經嘗試併成功地追加到HTML元素,但在字符串格式。

+0

我也是,當我在成功功能上設置一個斷點並在devtools中逐步完成時,它神奇地開始工作。 – 2014-12-04 04:06:45

1

你應該嘗試這樣的:

var output=""; 
 
\t var data="[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/galloping-rider-and-other-figures.jpg\", \"title\": \"Galloping Rider and other figures\"}, \"model\": \"serve.art\", \"pk\": 63057}]"; 
 
\t data = JSON.parse(data) 
 
for(x in data){ 
 
\t console.log(data[x]); 
 
output=output+"Artist:"+data[x].fields.artist+"<br>"+"Link:"+data[x].fields.link+"<br>"+"Title:"+data[x].fields.title+"<br>"+"Model:"+data[x].model+"<br>"+"PK:"+data[x].pk+"<br>"; 
 
\t 
 
} 
 
\t \t $('#output').html(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="output"></div>

+0

直到我運行devtools並設置斷點和其他東西時,該代碼才工作。現在它可以工作。我的瀏覽器出現了什麼問題,它一直這樣做? – 2014-12-04 04:26:18