【Django】ajax sample

【url】

url(r’^_sample/$’, ‘_sample’),
url(r’^_sample_json/$’, ‘_sample_json’),

 

【html】

<!DOCTYPE html>

{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% load staticfiles %}

<html lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<meta charset=”utf-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<meta name=”description” content=””>
<meta name=”author” content=””>
<link rel=”icon” href=”http://getbootstrap.com/favicon.ico”>

<title>SENSOR NETWORKS</title>

</head>

<body data-spy=”scroll”>

<div class=”container”>
<h3>SAMPLE</h3>
</div>

<!– BUTTON –>
<form role=”form”>
<button id=”bt_json” type=”button” class=”btn btn-default”>modal</button>
<button id=”bt_django” type=”button” class=”btn btn-default”>django</button>
</form>

<!– DIALOGS –>
<div>
<div id=”dialog” class=”modal fade”>
<div class=”modal-dialog”>
<div class=”modal-content”>
<div class=”modal-header”>
<button type=”button” class=”close” data-dismiss=”modal” aria-hidden=”true”>&times;</button>
<h4 class=”modal-title”>User Information</h4>
</div>
<div id=”dymanic_data” class=”modal-body”>

<!– dynamic data –>

</div>
<div class=”modal-footer”>
<button type=”button” class=”btn btn-default” data-dismiss=”modal”>Cancel</button>
<button type=”submit” class=”btn btn-primary”>Update</button>
</div>
</form>
</div>
</div>
</div>

<!– javascript –>
<script src=”{{ STATIC_URL }}/static/js/jquery.min.js”></script>
<script src=”{{ STATIC_URL }}/static/js/bootstrap.min.js”></script>
<script type=”text/javascript”>

$(document).ready( function() {

$(‘#bt_json’).click(function(){

$.getJSON(“../_sample_json”, function(json){

buf = “”
buf += “<ul>”;
for(i = 0 ; i < json.projects.length; i++){
buf += “<li>”
buf += json.projects[i].name
buf += “</li>”
}
buf += “</ul>”;
$(‘#dymanic_data’).html(buf);
})
$(“#dialog”).modal(“show”);
})
$(‘#bt_django’).click(function(){

$(“#dymanic_data”).load(“../_sample”);
$(“#dialog”).modal(“show”);
})

})

</script>
</body>
</html>

 

【view】

def _sample(request):

objs = Project.objects.all().order_by(‘name’);
return render_to_response(‘sn/modal_project.html’, {‘object_list’: objs})
def _sample_json(request):

resp = {}
arr = [];
objs = Project.objects.all().order_by(‘name’);
for o in objs:
p = {}
p[‘name’] = o.name
arr.append(p);
resp[‘projects’] = arr

return HttpResponse(json.dumps(resp), mimetype=”application/json”)

 

【html】dynamic data

{{ object_list|length }}
<ul>
{% for o in object_list %}
<li>{{ o.name }}</li>
{% endfor %}
</ul>

 

Leave a Reply