将AJAX数据发送到Django视图

时间:2018-01-24 05:47:31

标签: jquery python ajax django

我正在尝试通过AJAX将文本从模板发送到视图并将其保存到文本文件中,但是,我无法让AJAX识别该视图。我有一个调试打印语句,不会发送(sys.stderr.write(repr("I'm in submit text") + '\n'))。我已经在GET函数之外测试了AJAX并且它可以工作。我认为必须是我的网址的问题,但我似乎无法找到问题。

views.py

def submit_text(request):
    text = ''
    sys.stderr.write(repr("I'm in submit text") + '\n')
    if request.method == 'GET':
        text = request.GET['submitted_text']
        sys.stderr.write(repr("Here") + '\n')
        downloads_folder = ('/Users/<username>/Downloads')
        file_path = os.path.join(downloads_folder, 'codetext.txt')
        f = open(file_path, 'w')
        f.write(text)
        f.close()
    return HttpResponse()

AJAX

$(document).ready(function(){
        $('#submit-button').click(function(){
            var text;
            text = editor.getValue();
            $.get('/assignments/submit/'), {submitted_text: text}, function(){
                $('#submit-button').addClass('btn-sm');
            };
        });
    });

申请网址

urlpatterns = [
    url(r'^$', views.user_login, name='user_login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^submit/$', views.submit_text, name='submit_text'),
    url(r'^(?P<assignment_name_slug>[\w\-]+)/$',
        views.show_assignment, name='show_assignment')

]

项目网址

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^assignments/', include('mainapp.urls')),
    url(r'^admin/', admin.site.urls),
]

解决:我使用JQuery slim作为Bootstrap的一部分,我需要缩小CDN

0 个答案:

没有答案