ajax接收django发送的json数据
首先django要有写发送json数据的方法
1 import simplejson 2 3 def sendjson(request): 4 ''' 发送json数据 ''' 5 result = {'username': 'username', 'password': 'password'} 6 result = simplejson.dumps(result) 7 8 return HttpResponse(result) 9 10 def index(request): 11 ''' 渲染sendjson.html模版页面 ''' 12 render_to_response('sendjson.html', locals())
sendjson.html
1 <html> 2 <body> 3 4 <script type='text/javascript'> 5 $(function(){ 6 $.ajax({ 7 type: 'POST', // 发送请求的方式 8 url: '{% url sendjson %}', // 发送请求 9 dataType: 'json', // 返回数据的格式 10 success: function(data){ // data 为json数据 11 $('#recive').html(data) 12 }, 13 }); 14 }); 15 </script> 16 17 <div id='receive'></div> 18 19 </body> 20 </html>
用json传数据的时候在数据量比较大的时候还是很爽的
jquery中有个方法是getJson()。是ajax函数的缩写。相当于:
1 $.ajax({ 2 dataType: 'json', 3 url: url, 4 data: data, 5 success: success, 6 })
每天一点点收获...