简体   繁体   English

在 Django 中通过 AJAX 调用 python 函数

[英]Calling a python function via AJAX in Django

I am sending a request via AJAX upon a button (whose id="transcript" ) click to trigger a function called transcript .我正在通过 AJAX 发送一个请求,点击按钮(其id="transcript" )触发一个名为transcript的函数。

AJAX AJAX

document.querySelector('#transcript').addEventListener('click', () => {
                        fetch(`transcript/${CNIC}`);
                        

views.py视图.py

def transcript (request, cnic):
    form = TranscriptForm()
    return render (request, "certificates/transcripts.html", {
        "form": form,
        "cnic": cnic
    })

The fetch request works fine, but the new page ie transcripts.html does not render.获取请求工作正常,但新页面,即transcripts.html不呈现。 I have to manually type the URL to update the view.我必须手动输入 URL 来更新视图。 Why is it happening, can anybody please explain?为什么会这样,谁能解释一下?

The output in console:控制台中的输出:

views.js:62 Fetch finished loading: GET "http://127.0.0.1:8000/transcript/1530660001979".

You can't redirect a user this way, but you can do something like redirecting a user in js after a successful response from the backend:您不能以这种方式重定向用户,但您可以在后端成功响应后执行类似在 js 中重定向用户的操作:

template.html:模板.html:

<!-- set the csrf token as a variable, then include script.js -->
<script> var csrf_token = "{{ csrf_token }}" </script>
<script src="{% static 'script.js' %}"></script>

script.js:脚本.js:

// execute on button click:
$('#button').click(function() {

  // send the ajax request:
  $.ajax({
    url : 'the_url',
    csrfmiddlewaretoken : csrf_token, // from the template
    type : 'POST',
    data : {
      'frontend_key' : 'frontend_value'
       ...
    }
    success : success_function // reference to function below:
  })
});

// executes on receiving a response from the backend:
function success_function(response) {

  // unpack response:
  backend_value = request.backend_key;
  ...

  // redirect user:
  window.location('the_new_url');

}

views.py:视图.py:

def transcript(request):

    # unpack request:
    frontend_value = request.POST['frontend_key']
    ...

    # do something:
    ....

    # pack response:
    response = json.dumps({
        'backend_key' : 'backend_value',
    })

    return HttpResponse(response)

An example一个例子

views.py视图.py

def returnSubCategories(request):
  category_request = request.GET.get('category',None)
  print(request.GET.get('category',None))
  subcategories =   SubCategories.objects.filter(category=category_request).values()
  subcategories_list = list(subcategories)

  return JsonResponse(subcategories_list,safe=False)

urls.py网址.py

url(r'^ajax/obtenersubcate/$',views.returnSubCategories,name='regresasubcategorias'),

code js代码js

$("#button").on('click',function(e){
    e.preventDefault();
    getList();
});

function getList() {
    axios({
        method:'get',
        url:'{% url "anuncios:regresasubcategorias" %}',
        params:{'category':1},
        responseType:'json'

    })
    .then(function(response){
        console.log(response);
    })
    .catch(function(error){
        console.log(error)
    })
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM