首先要引入jquery文件,可以引入在线的,也可以下载离线的 添加进自己staticfiles
这里演示的是添加离线的
<script src={% static 'js/jquery-2.1.1.min.js' %}></script>
注意这句是要添加到自己写的ajax jquery脚本前。
然后HTML表单如下:
- <form id="sqlform" method="post">
- {% csrf_token %}//防止请求伪造
- <input id="sqlinput" name="sqlinputname" style="width:95%;height:30px;background-color:#fefcff; border:#d1d0ce 1px solid;" type="text"></input>
- <button id="submit" style="width:50px;height:30px;" type="submit" >查询</button>
- </form>
- <pre id="sql_output" style="width:95%;margin-top:10px;height:100%;background-color:#fefcff; border:#d1d0ce 1px solid;" ></pre>
如果你在settings里边没有注释掉
'django.middleware.csrf.CsrfViewMiddleware',
你的jquery里边需要添加上这句,
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
然后整个ajax脚本,这里写的比较就简单主要突出与django的通信:
- <script>
- $(document).ready(function(){
- $.ajaxSetup({
- data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
- });
- $('#sqlform').submit(function(){
- var input = $("#sqlinput").val(); //获得form中用户输入sql语句注意 与你html中input的id一致
-
- $.ajax({
- type:"POST",
- data: {input:input},
- url: "", //后台处理函数的url 这里用的是static url 需要与urls.py中的name一致,或者直接写http地址
- cache: false,
- dataType: "html",
- success: function(ret){ <span style="font-family: Roboto, Helvetica, Arial, sans-serif;">//成功时弹出view传回来的结果即后端处理函数中HttpResponse的返回值</span>
- $('#sql_output').html(ret)
- // var content= $("#sqlinput");
- // $('#sql_output').append(content.val());
-
- },
- error: function(){
- alert("false");
- }
- });
- return false;
- });
-
- });
- </script>
接下来写我们后端的view.py 中的后端处理函数
def comments_upload(request):
if request.method == 'POST':
print "it's a test" #用于测试
print request.POST['input'] #测试是否能够接收到前端发来的input字段
return HttpResponse(<span style="line-height: 1.42857;">request.POST['input']</span><span style="line-height: 1.42857;">) #最后返会给前端的数据</span>
else:
return HttpResponse("<h1>test</h1>")
由于有中文所以views.py 开头加上
#coding=utf8
注意:ajax POST的url页面不是接收输入的页面。。。。。。这地方我宰了第二次了。。。。。。。。也就是
comments_upload函数是POST请求的页面对应的处理函数,而我们提交请求的页面(即上面的HTML)只是用于提供输入和接收处理结果的页面,所以不能把接收处理语句写在上面的HTML中,需要将它写到comments_upload函数所在的页面。