如何在django中从javascript调用python函数?

问题描述 投票:0回答:1

我正在制作一个立方体计时器应用程序。我有一个 django 应用程序,它加载 python 函数,该函数从

views.py
中的文件生成打乱。我有一个 JS 文件,通过单击空格键来运行计时器。我想在每次计时器停止时生成新的打乱。

如何做到这一点?

这是我的

views.py
文件:

from .scramble_generator import *

def home(request):
    s = scramble_replace(scramble_gen())
    scramble = sprint(valid(s))
    return render(request, 'timer/index.html', {'scramble':scramble})

main.js

let state = 'stopped';

const transitions = {
  waiting: state => ResetTimer(),
  started: state => StartTimer(),
  stopped: state => PauseTimer(),
};

document.addEventListener('keydown', changeState);
document.addEventListener('keyup', changeState);

function changeState({code, repeat, type: action}){

  if(code !== 'Space' || repeat){
    return;
  }

  // this allows to have more event types and states in the future without cluttering
  const actions = {
    keydown: () => state === 'stopped' ? 'waiting' : 'stopped',
    keyup: () => state === 'stopped' ? state : 'started',
  };

  // determine the next state 
  const next = actions[action]();
  // if the next state is different, commit it to the current and execute transition
  next === state || transitions[state = next](state);

}
python django
1个回答
-1
投票

您可以通过在 Django 中创建一个端点,然后在需要调用该函数时从 javascript 发出 http 请求来实现。

这是你可以做到的

在 Django urls.py 文件中创建一个新的 URL 模式以映射到 API 端点:

from django.urls import path
from . import views

urlpatterns = [path('api/function/', views.home, name='get_function'),# other URL patterns...]

添加此内容后,您可以像这样从 javascript 调用它:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/function/');
xhr.onload = function() {
    if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        var functionName = response.function;
        // Now you can use the functionName as desired in your JavaScript code
        // For example, you can call the function
        window[functionName]();
    } else {
        console.log('Error:', xhr.status);
    }
};
xhr.send();
© www.soinside.com 2019 - 2024. All rights reserved.