Ajax例子,views返回,html接收数据
Ajax例子,views返回,html接收数据
views
from django.shortcuts import render,HttpResponse,render_to_response import json # Create your views here. def ajax(request): if request.method == 'POST': print request.POST ret = {'status':0, 'msg':'dsafasdf', 'data':[11,22,3,5,6,7,4], } return HttpResponse(json.dumps(ret)) else: return render_to_response('ajax.html')
ajax.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input id="na" type="text" /> <input type="button" value="ajax请求" /> <script type="text/javascript" src="/static/js/jquery-2.2.3.js"></script> <script type="text/javascript"> $(document).ready(function () { $("input[type='button']").click(function () { var temp = $("#na").val(); $.ajax({ url:'/app02/ajax/', type:'POST', data:{dat:temp}, success:function (arg) { //arg 是服务器端的返回值 var obj = jQuery.parseJSON(arg); //jQuery的parseJSON方法,注意大写 console.log(obj.status); console.log(obj.data); console.log(obj.msg); console.log('success'); $("#na").attr("id",obj.msg) }, error:function () { console.log('failed') } }) }) }) </script> </body> </html>