What I want is, at the front-end, when the button pressed, retrieve the data from the back-end using Ajax, then attach them to a table. I'm using Django 1.9.
I managed to do so. However, each value does not match each column, just as the picture shows:
So that is my problem. CDK should be name, instead of price.
In views.py, I have:
def ajax_dict(reuqest):
dicWCWishlist = [{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong", "Price":"$$999", "Addin-Date":"1980-3-9"}]
return JsonResponse(dicWCWishlist, safe = False)
In runAjax.html, I have:
$("#btnJJDBZ").click(function() {
// alert("Boom!");
$.get("../ajax_dict/", function(res) {
for(var i = 0; i < res.length; i++) {
var ntr = $("<tr></tr>");
$.each(res[i], function(key, value) {
var ntd = $("<td></td>")
ntd.html(value);
ntr.append(ntd);
})
$("#tbodyWishlist").append(ntr);
}
});
});
Besides, more strangely, whenever I modify the views.py file, the received data order randomly change again. Like when I add a space at any end of the line, or I change price $749 to $750, save and refresh the page, then the price column data moved to Add-in Date, or randomly under some column I don't know.
-------------------------------------------------------------------------
The problem is solved for now, thanks to @luke_aus 's help.
In runAjax.html, change the jquery code with it follows:
$("#btnJJDBZ").click(function(){
$.get("../ajax_dict", function(res) {
$.each(res, function(){
$.each(this, function(key, value){
var ntr = $("<tr></tr>");
var ntd1 = $("<td class='CDK'></td>");
var ntd2 = $("<td class='Price'></td>");
var ntd3 = $("<td class='Addin-date'></td>");
$.each(this, function(key, value){
switch(key){
case "CDK":
ntd1.html(value);
break;
case "Price":
ntd2.html(value);
break;
case "Addin-Date":
ntd3.html(value);
break;
}
})
ntr.append(ntd1).append(ntd2).append(ntd3);
$("#tbodyWishlist").append(ntr);
});
});
});
I changed the data format, too.
dicWCWishlist = {"list":[{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong1", "Price":"$$999", "Addin-Date":"1980-3-9"}]}
What I did is basically,
- Create tr and 3 tds in advance
- When key comes, manually tell what key it is (using switch)
- Change the corresponded cell with correct value (using html())
However, the question is still there!
Why was my data order random?
What did JsonResponse do to my JSON ?