码迷,mamicode.com
首页 > Web开发 > 详细

ajax Post数据,并得到返回结果

时间:2016-04-28 12:15:06      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:

urls.py:

from django.conf.urls import url
from aptest import views as aptest
urlpatterns = [
    url(r^$, aptest.index, name=index),

]

编辑views.py,定义主页:

from django.views.decorators.csrf import csrf_exempt #导入csrf_exempt模块 

@csrf_exempt #由于csrf机制,在此需要调用该装饰函数,否则在ajax post数据的时候会提示403 forbiddon
def index(request): #主页
    print request.method
    a=request.POST.get(a)
    b=request.POST.get(b)
    print a,b
    if a is not None and b is not None:
        ret=int(a)+ int(b)
        return HttpResponse(str(ret)) #执行到此处,后面的代码不会再继续执行
    context={}
    return render(request,aptest/index.html,context)

编辑模板index.html:

在其form中定义action值,指向当前页面,则在ajax post data时无需再定义url,默认将把数据提交到当前页面。

{% extends "base.html" %}
{% block title %}aptest index{% endblock %}
{% block content %}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script> <!--应用的js脚本文件-->

<p>请输入两个数字</p>
<form action="{% url ‘aptest:index‘ %}" > <! -- 此处action表示该form提交到的页面,此处含义为 aptest应用的index页面。如果action为空,则需要在ajax post的url中进行定义。 method不需要定义,在ajax里面定义即可 -->
  {% csrf_token %}
    a: <input type="text" id="a" name="a" > <br>
    b: <input type="text" id="b" name="b"> <br>
   
    <p>result: <span id=‘result‘></span></p>
    <input type="button" id=‘sum‘ name=‘sum‘ value="cacl">
</form>
<div id="box"></div>

{% endblock %}

base.html:

{% include ‘header.html‘ %}
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% include ‘userauth.html‘ %}
    <h1>My Test site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site2.</p>
    {% endblock %}
    <!-- {% include ‘footer.html‘ %} -->
</body>
</html>

header.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>

编辑index.js,定义js函数:

$(document).ready(function(){

  $(‘p‘).css(‘color‘,‘red‘)
  $(‘form input[type=button]‘).click(function(){  //绑定form中tpye=button的input标签
    a=$(‘form input[name=a]‘).val();
    b=$(‘form input[name=b]‘).val();
    // alert(a);
    //alert(b);
    $.ajax({
      type: ‘POST‘,
      //url: ‘/aptest/‘, 由于在index.html的form的action已经定义了该url,所以此处不需要再定义。 这段js代码如果直接写在index.html中,则该url也如此,不变
      data: {
        a:a,
        b:b
      },
      success:function(response,stutas,xhr){
        $(‘#result‘).html(response); //将index view的返回值绑定到id=result的内容中。response参数表示所有从后端返回的值
        alert(stutas); //执行成功返回状态success
      },
      error:function(xhr,errorText,errorStatus){
        alert(xhr.status+‘:‘+xhr.statusText); //数据提交失败返回403 forbidden
      }
    });
  });

执行结果:提交a=22,b=3,result返回25

技术分享

 

ajax Post数据,并得到返回结果

标签:

原文地址:http://www.cnblogs.com/dreamer-fish/p/5441898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!