JsonResponse | Django开发
2021-05-18 13:30
标签:nbsp 字符 cal log input lang 类型 val cat JsonResponse | Django开发 标签:nbsp 字符 cal log input lang 类型 val cat 原文地址:http://www.cnblogs.com/pymkl/p/7736564.html # 浏览器中使用javascript发起ajax请求时,返回json格式的数据,此处以jquery的get()方法为例;
# 类JsonResponse继承自HttpResponse对象,被定义在django.http模块中.接收字典作为参数;
# JsonResponse对象的content-type为“application/json”;
1.前端页面
================================================================================
DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>Titletitle>
script src="/static/jquery-1.12.4.min.js">script>
script>
$(function () {
$(‘#cal‘).click(function () {
// 获得a、b值
a = $(‘#a_val‘).val();
b = $(‘#b_val‘).val();
$.get(‘/ajax/‘, {‘a‘: a, ‘b‘: b}, function (data) {
$(‘#result‘).val(data.result);
});
});
});
script>
head>
body>
table>
tr>td>a:td>td>input type="text" name="a" id="a_val">td>tr>
tr>td>b:td>td>input type="text" name="b" id="b_val">td>tr>
tr>td>input type="button" id="cal" value="计算">td>td>input type="text" id="result">td>tr>
table>
body>
html>
================================================================================
2.视图函数
================================================================================
def ajax(request):
# 获得请求参数都是字符串类型
a = request.GET.get(‘a‘)
b = request.GET.get(‘b‘)
if a and b:
ret = ‘运算: %d + %d = %d‘ % (int(a), int(b), int(a) + int(b))
print("ret:", ret)
return JsonResponse({‘result‘: ret})
else:
return render(request, ‘ajax.html‘)
================================================================================
下一篇:quartz.net 入门
文章标题:JsonResponse | Django开发
文章链接:http://soscw.com/index.php/essay/87215.html