django + jQuery AJAX POST数据

废话少说,直接代码伺候:

views:

from django.http import JsonResponse
def test_post(request):
    name = request.POST[‘name‘]
    city = request.POST[‘city‘]
    qq = request.POST[‘qq‘]
    dict = {‘name‘:name,‘city‘:city,‘qq‘:qq}
    return JsonResponse(dict)
def test(request):
    return render(request,‘app/accounts/test.html‘)

urls:

urlpatterns = [
    url(r‘^test/$‘,views.test),
    url(r‘^test/post$‘,views.test_post,name=‘test_post‘),
]

test.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>testajax</title>
</head>
<body>
<div id="test"><h2>请点击下面的按钮,通过jQuery AJAX接收数据</h2></div>
<div id="result"></div>
<button id="btn1" type="button">获取服务器数据</button>
<script src="{% static ‘jquery/jquery-2.2.0.min.js‘ %}"></script>
<script src ="{% static ‘js/csrf.js‘ %}"></script>
<script>
    $().ready(function(){
        $(‘#btn1‘).click(function(){
            $.post("{% url ‘test_post‘ %}",
                    {
                        csrfmiddlewaretoken:"{{ csrf_token }}",
                        name:"dodo",
                        city:"Ganzhou",
                        qq:"12519460"
                    },
                    function (data,status) {
                        $.each(data,function(key,value){
                            $("#result").append(status +":"+key +":"+value +"<br/>")
                        })
                    }
            )
      })
    })
</script>
</body>
</html>

关于POST数据:csrf_token报错问题,参照自强学堂http://www.ziqiangxuetang.com/django/django-csrf.html。同时把js/csrf.js代码如下:

/**
 * Created by dodo on 2016/1/29.
 */
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != ‘‘) {
            var cookies = document.cookie.split(‘;‘);
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + ‘=‘)) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = ‘//‘ + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + ‘/‘) ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + ‘/‘) ||
            // or any other URL that isn‘t scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie(‘csrftoken‘));
    }
});

最后效果图:

时间: 2024-10-26 10:01:37

django + jQuery AJAX POST数据的相关文章

Django+JQuery+Ajax+Post方案中的问题及解决

遇到的问题 请求发送后,服务端无响应 Django对于POST请求会检查请求来源,表单方式提交时: 在Form内添加 `{% csrf_token %}` 标签: request响应函数前,添加 `@csrf_exempt` ; Jquery POST 方式提交时,在服务端添加了 @csrf_exempt ,在Django1.5版本后,无法直接通过POST获取参数,通过`raw_data = request.body` 获取数据时,出现如下错误提示: Exception: You cannot

django + jQuery AJAX初试

经过反复的测试,终于在django+jQuery AJAX成功返回服务器数据,本次测试在/static/test/test.txt test.txt: txt = {'1':'re','2':'qqq','3':'www','4':'rere'} views: def test(request): return render(request,'app/accounts/test.html') urls: urlpatterns = [ url(r'^test/$',views.test), ]

MVC使用jQuery.ajax()删除数据

jQuery.ajax()可以简写为$.ajax().以前有写过MVC删除的实现,如<MVC实现删除数据库记录> http://www.cnblogs.com/insus/p/3368042.html 和<MVC 5显示.创建.编辑.删除等功能实练>http://www.cnblogs.com/insus/p/3372916.html .不过此次Insus.NET想使用jQuery.ajax()方法来实现. 能实现到此功能,也有遇上很多困难以及花费很多时间.当你看到此篇时,你会看到

django 使用jquery ajax post数据问题

django 开启了CSRF功能导致jquery ajax post数据报错 解决方法在post数据里引入csrfmiddlewaretoken: '{{ csrf_token }}'},同时需要在form表单中设置{% csrf_token %} <script src="/static/jquery/dist/jquery.min.js"></script> <script> $(function(){ $("#postset"

django jquery ajax 知识点

示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <div id='d'>1</div> <div> <div id='i1' name='123'> <h1>fff</h1> 2 <a id='v'>ff</a> <h1>fff</h1> </div> <div> 大丰收的 <div>3</div> <div

JQuery Ajax 获取数据

前台页面:   对一张进行查询,删除,添加 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src=

jQuery ajax大数据量each输出 list

<script>var tbodystr = "";$.ajax({                type: "get",                url: "gettable.ashx",                cache: false,                datatype: "json",                success: function(msg) {        

jquery ajax 传数据到后台乱码的处理方法

前台页面先对中文进行编码,如下红色字体: function saveCommentTemplate() { $.ajax({ cache : false, type:'get', dataType:'json', url:'comment/insert', contentType:'application/json;charset=UTF-8', data:{name:encodeURI($("#name").val()), content:encodeURI($("#con

JQuery ajax 保存数据,删除数据

<script type="text/javascript"> //ajax 提交表单数据 $("#add_budget_submit").click(function () { $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, }); $.ajax({ url: '{{ request.path }}', type: 'POST', data: $('#budgetForm')