簡體   English   中英

我如何使用腳本在腳本文件或views.py中運行python函數來不加載頁面

[英]How Can I run a python function in script file or in the views.py using javascript for not loading the page

我有一個Django頁面,該頁面的表單帶有一個按鈕,該按鈕調用views.py中的函數,但是我想通過運行python腳本函數來驗證表單的一些輸入文本(在views.py中,或者我可以分離該函數在另一個文件中),但我不想加載該頁面。 我在哪里以及如何使js代碼運行此功能?

為視圖功能創建一個新的URL,以驗證輸入。

path('ajax/validate_input/', views.ValidateInput.as_view(), name='my_ajax_url'),

views.py進行驗證,然后返回JsonResponse

from django.views import View
from django.http import JsonResponse

class ValidateInput(View):
    def post(self, request):
        # Do validation
        return JsonResponse({
            'valid': True,
            'message': 'Invalid Characters',
        })

現在,在模板中編寫js代碼,該代碼將對該URL發出Ajax請求。

根據收到的響應,在成功使用ajax時使用js更改您的網頁。

// add jQuery
// put the code below inside an event handle, maybe on input change
$.ajax({
    url: {% url 'my_ajax_url' %},
    method: 'POST',
    data: {
        body: body,
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(data){ 
        console.log(data.valid);
        console.log(data.message);
        // do stuff to change your webpage here
    }
});

我建議驗證輸入更改時的輸入,但是如果您想從Submit中進行輸入,則為表單Submit添加一個事件處理程序。 使用event.preventDeafault來阻止表單提交,然后執行ajax的操作,並根據收到的json進行其他操作。 也許如果valid = true則繼續操作;或者,如果valid = false則在輸入框下方顯示json中收到的消息。

您可以在專用的Python視圖中呈現表單,然后通過Javascript中的Ajax調用它。

在這種情況下,您應該:

  • 創建表格
  • 渲染成字符串
  • 將呈現的表單返回為json

如果通過GET方法調用它,則使用初始值(沒有警告或錯誤消息)呈現表單。

如果使用的方法是POST,則可以從請求中獲取值並呈現表單(包括驗證消息)。

這可能是Django視圖的樣子:

import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def my_view(request):

    if request.method == "GET":    
        form = MyForm()
    elif request.method == "POST":
        form = MyForm(data=request.POST)

    form_context = {'form': form}    
    form_html = render_to_string('form.html', form_context)

    json_response = json.dumps(form_html, separators=(',', ':'))
    return HttpResponse(json_response)

在Javascript端通過GET(使用JQuery.getJSON):

$.getJSON('/url/path/to/my-view',
          function(data) {
              var form_html = decodeURIComponent(data.form);
              $("form#my-form-css-selector").html(form_html);
});

並通過POST在Javascript端(使用JQuery.post):

$.post('/url/path/to/my-view',
       $("form#my-form-css-selector").serialize(),
       function(data) {
           var form_html = decodeURIComponent(data.form);
           $("form#my-form-css-selector").html(form_html);
       },
       "json"
);

您可以檢查Django視圖Django render_to_stringJQuery.getJSONJQuery.post文檔頁面以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM