为什么这两种形式在Django中无法与ajax一起使用?

时间:2019-02-06 16:36:08

标签: javascript ajax django

我正在django上开发应用程序,并且遇到了Ajax的奇怪问题。在我的网站上,应该使用Ajax处理4个表格。其中两个工作得很好。但是还有2个人没有听到  关于Ajax。考虑工作形式和非工作形式。

views.py

查看工作表

def login_user(request):
    form = LoginForm(request.POST)
    context = { 'form': form, }

    if request.method == 'POST' and form.is_valid():
        username = form.cleaned_data['user_login']
        password = form.cleaned_data['user_password']
        user = authenticate(username=username, password=password)
        response_data = {}
        if user and user.is_active:
            login(request, user)
            response_data['result'] = 'Ok'
        else:
            response_data['result'] = 'Bad'
        return HttpResponse(json.dumps(response_data))  
    else:
        return redirect('index') 

查看无效表格

 def add_new_station(request, add_station_slug):
        form = AddStationForm(request.POST)
        myuser = get_object_or_404(User, id=request.user.id)
        print(request.user)
        if request.method == 'POST' and form.is_valid():
            response_data = {}
            UserStation.objects.create(
                station=Station.objects.get(slug=add_station_slug),
                impressions=form.cleaned_data['impressions'],
                list=UserStationsList.objects.get(user=myuser)
                response_data['result'] = 'Ok'
            )
            return HttpResponse(json.dumps(response_data)) 
        else:
           return redirect('index')

urls.py

    urlpatterns = [
        path('', index, name='index'),
        path("add-in-list/<str:add_station_slug>/", add_new_station, name='new_station'),
        path('login/', login_user, name='login_action'),
        ...
]

html

html工作表

<form id="login_form" action="{% url 'login_action' %}" method="post">                                       
   {% csrf_token %}                                          
   {{ formlogin }}                                   
    <div class="text-center">
        <button type="submit" class="btn btn-dark mt-2">Entry</button> 
    </div>                                   
</form>

html无效表格

<form id="add_station_form" action="{% url 'new_station' choice_station.slug %}" method="post">
     {% csrf_token %}
     {{ formaddstaion }}
     <div class="text-center">
          <button type="submit" class="btn btn-outline-success mt-2">I visited this  station</button>
     </div>
 </form>

mian.js

脚本工作表

$('#login_form').submit(function() {
    $.ajax({ 
        data: $(this).serialize(), 
        type: $(this).attr('method'), 
        url: $(this).attr('action'), 
        success: function(response) {
            data = JSON.parse(response)
            if (data['result'] === "Ok"){
              $('.login-message').hide()
              location.reload()
            }
            else{
              $('.login-message').show(100).html('wrong data')
            }
        }
    });
    return false;
});

脚本无效形式

$('#add_station_form').submit(function() {
      $.ajax({ 
          type: $(this).attr('method'), 
          url: $(this).attr('action'), 
          success: function(response) { 
              data = JSON.parse(response)
              alert('data') // try check, but ajax don't reach here
          }
      });
      return false;
    }); 

在第一种情况下,一切运行正常,在第二种情况下,Ajax根本无法启动(我只是使用HttpResponce重定向到页面。那么,出了什么问题?

1 个答案:

答案 0 :(得分:0)

在第二种形式中,您尝试使用ajax将POST请求发送到Django视图,但是众所周知 POST请求的URL中不包含参数,因此您需要删除该参数从网址中进行一些必要的更改,如下所示:

删除网址中的参数,然后在表单中添加一个包含该参数的隐藏输入字段。

    <form id="add_station_form" action="{% url 'new_station' %}" method="post">
       {% csrf_token %}
       {{ formaddstaion }}
      <input type="hidden" name="add_station_slug" value="{{choice_station.slug}}" readonly>
      <div class="text-center">
        <button type="submit" class="btn btn-outline-success mt-2">
             I visited this  station
        </button>
      </div>
    </form>

@Borut中的ajax注释中,您需要像这样将数据传递给ajax请求:

    $.ajax({ 
       type: $(this).attr('method'), 
       url: $(this).attr('action'), 
       data: $(this).serialize(),
       success: function(data) { alert(data.response);  }
    });

现在在urls.py内部删除如下参数:

    urlpatterns = [
      ...
      path("add-in-list/", add_new_station, name='new_station'),
      ...
    ]    

现在终于可以在视图中提取参数并使用它了:

    from django.http import JsonResponse 
    # from Django 1.7 onward you should use JsonResponse instead of HttpResponse
    # so that you don’t need to serialize the data before returning the response object.

    def add_new_station(request):
       response_data = {'response': 'Something went wrong!'}
       form = AddStationForm(request.POST)
       myuser = get_object_or_404(User, id=request.user.id)
       if request.method == 'POST' and form.is_valid():            
          slug = request.POST.get('add_station_slug')
          UserStation.objects.create(
            station=Station.objects.get(slug=slug),
            impressions=form.cleaned_data['impressions'],
            list=UserStationsList.objects.get(user=myuser)                
          )
        response_data['response'] = 'UserStation Created Successfully!'
    return JsonResponse(response_data)