【问题标题】:Django. How to call a python function from HTML button without reloading page?姜戈。如何在不重新加载页面的情况下从 HTML 按钮调用 python 函数?
【发布时间】:2020-03-27 03:35:57
【问题描述】:

我想在后端调用 python 函数而不重新加载页面。 像这样:

index.html

<button name="button" onclick="run_function(param1, param2)">Run</button>

views.py

some_function(param1, param2):

    return(param1, param2)

请不要回答“努力学习整个 django 文档!”我已经做了一些研究,但是我还没有为我的案例找到任何工作代码。

【问题讨论】:

  • 您需要使用 Ajax。不,这与 Django 文档无关。
  • 我知道这一点,但是我尝试过的每个 javascript7ajax 代码都发布在网上和 stackoverwflow 上,但从来没有真正为我工作过。而且我也不想研究整个 ajax、js 和 jquery 文档。
  • 不幸的是,如果你想这样做,你将不得不学习。

标签: python django ajax django-forms django-views


【解决方案1】:

所以最后我自己解决了这个问题。 This 帮了很多忙。

index.html

<button name="button" onclick="run_function(param1, param2)">Run</button>

script.js

function run_function(param1, param2){
    console.log("running");
    $.ajax({
        url : "random_url/", // the endpoint
        type : "GET", // http method
        data : { param_first : param1, 
                param_second : param2 }, // data sent with the get request

        // handle a successful response
        success : function(json) {
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

views.py

from django.http import HttpResponse
import json

def some_func(request):
    if request.method == 'GET':
        param1 = request.GET.get('param_first')
        param2 = request.GET.get('param_second')
        print(param1, param2)


        response_data = 'successful!'

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

urls.py(不知道这一步是否必要)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('random_url/', some_func)
]

还要确保您获得了未压缩的 jquery 包。

【讨论】:

  • 嗨。 jsonscript.js 中来自哪里?
  • @TheSprinter 在views.py 中你会在函数内部看到一个发送json 响应的HttpResponse 函数。
【解决方案2】:

python 代码实际上是在服务器上运行的。这就是为什么您需要“重新加载”页面以运行 python 代码的原因。实际上,当您这样做时,您正在向服务器发送一个请求,该服务器将运行 Python 代码并返回一个正确填充的 HTML 页面作为响应。

如果你想在浏览器中运行一些代码,你可以使用 JavaScript 定义一个函数,当点击事件被触发时会被调用。

更多信息:

Article about Client-Server architecture

Introduction to JavaScript

【讨论】:

  • 你能给我写一个示例代码吗?我可以使用ajax。我知道这一点,但是我尝试过的每个 javascript7ajax 代码都发布在网上和 stackoverwflow 上,但从来没有真正为我工作过。您发布的链接并不是真正有用的,也不是真正针对我的 django 问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
相关资源
最近更新 更多