I want to append a json object to the page. I get it successfully via ajax, but it's not showing up.
<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
}
});
}
The response appears to be in one long escaped string when I view the response and preview in 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}
How can I wrangle this into something usable?
use
JSON.parse
and you'll get the data.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
No you cannot append an object to a HTML element.
Don't parse the JSON , just append in the format( string ) as you are getting.
I have tried and successfully appended to the HTML element but in the string format.
you should try like this:
var output=""; 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}]"; data = JSON.parse(data) for(x in data){ 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>"; } $('#output').html(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="output"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.