JSON帖子没有得到django视图的响应

时间:2014-05-26 01:58:32

标签: jquery ajax django python-2.7 django-views

所以我尝试了一个简单的JSON帖子。但我对django方面的看法根本没有回应。 JavaScript的:

$(function(){
var arr = { 'file': "print \"It works!\"", 'fileName' : "JSONtest", 'fileExt':".py" };

$.ajaxSetup({ 
 beforeSend: function(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;
     }
     if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
         // Only send the token to relative URLs i.e. locally.
         xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
     }
 } 
});
$.ajax({
    url: '/au',
    type: 'POST',
    data: JSON.stringify(arr),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
        alert(data['link']);
    }
    });
});

view.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.core.files.base import ContentFile
from django.views.decorators.csrf import ensure_csrf_cookie

from quickpad.models import FileLink

from mimetypes import types_map

from random import randint

def upload(request):
    print 'hi'
    genId = ''
    try:
        data=json.loads(request.body)
        file=data['file']
        name=data['fileName']
        ext=data['fileExt']
        newFile = FileLink(fileName=name,fileExt=ext)
        newFile.file.save(name,ContentFile(file))

        while (True):
            genId = ''.join([alphaNum[randint(0,61)] for i in xrange(8)])
            if len(FileLink.objects.filter(fileId=genId)) == 0: break
        print genId
        newFile.fileId = genId
        newFile.save()

    except:
        print 'nope'
    response = HttpResponse()
    csrf(response)
    response['link'] = genId
    return response

印刷品&#34; hi&#34;声明不显示也不会创建任何新对象。你能帮忙的话,我会很高兴。谢谢!

1 个答案:

答案 0 :(得分:0)

很抱歉延迟,问题是我的url.py中的订购默认r&#39; ^ $&#39;由于某种原因,他正在弄乱另一个网址。经过2个小时的调试后,我终于发现了错误(很难调试,因为没有显示错误,也没有任何调试文本)。对不起,这是我的第一个Django应用程序。