Javascript 在django中使用ajax处理表单请求

Javascript 在django中使用ajax处理表单请求,javascript,jquery,ajax,django,Javascript,Jquery,Ajax,Django,当我从表单发送请求时,ajax有问题,因为它没有从表单中获取值 这是我的视图代码 def create(request): if request.method == 'POST': msg_text = request.POST.get('the_massage') data = {} form = ChatApp(message=msg_text, user=request.user) form.save()

当我从表单发送请求时,ajax有问题,因为它没有从表单中获取值

这是我的视图代码

def create(request):
    if request.method == 'POST':
        msg_text = request.POST.get('the_massage')
        data = {}
        form = ChatApp(message=msg_text, user=request.user)
        form.save()
        data['message']=form.message
        data['user']=form.user.username
        return JsonResponse(data)
    else:
        return JsonResponse({'nothing coming thrue'})
它应该得到_按摩变量,但它给我空值

这是我的ajax函数:

    $(function () {


  $('#main-form').on("submit"  ,function () {
    console.log("create function is here");
    var form = $(this);
    $.ajax({
      url: form.attr('action'),
      type: form.attr('method'),
      data: {the_massage:$('#msgbox').val()},
      dataType: 'json',

      success: function(json) {

        console.log(json);
        console.log('success');
      },
      error: function(error){
        console.log('we have error');
      },
    });
  });

});
当我在控制台中记录值时,它只是在控制台中通过 请帮帮我 并在控制台中显示:

解释为文档但使用MIME类型传输的资源 应用程序/json:“”


在事件中调用函数:

$('#main-form').on("submit"  ,function (event) {
    event.preventDefault();
    console.log('submited');
    console.log($('#msgbox').val())
    created(); 
 });

我在这里看到许多可能的问题

1) 仅针对开发人员建议,从视图中删除
@login\u required
(如果有),并添加
@csrf\u employ
,以避免开发人员出现此问题

2) 请查看您视图中的
request.body


3) 如果第1点和第2点不起作用,请输入此调用的服务器响应:
POST localhost:8000/create 403(禁止)

这是书面回答:我解决了这个问题,现在它在git hub上运行了

第一个在ajax中编写url的方法是错误的:url:“/create”,url没有错,它的工作很好,但是数据没有出现through@MhadiAhmedCharlizard的意思是,硬编码url不是一个好的做法。我已经对它进行了同样的编辑,直到你的url不正确,它根本不会影响ajax功能。。然后是部分数据没有出现现在我在控制台中有这个错误:jquery-3.1.1.min.js:4 POST 500(内部服务器错误),但是,服务器的响应是什么?这一行是一个错误
返回JsonResponse({'nothing coming throue'})