python - Django 。如何从 HTML 按钮调用 python 函数而不重新加载页面?

标签 python django ajax django-forms django-views

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

index.html

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

views.py

some_function(param1, param2):

    return(param1, param2)

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

最佳答案

所以最后我自己解决了这个问题。 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 包。

关于python - Django 。如何从 HTML 按钮调用 python 函数而不重新加载页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59140343/

相关文章:

python - Arduino、Raspberry Pi 和 HTML 页面

python - 将字符列编码为序数,但保持数字列相同

php - Safari 错误。 JavaScript ajax json 对象 - 无法获取属性。对象可能不再存在

python - 使用tkinter gui循环在sqlite3数据库中出现操作错误(语法)

python - 为什么Python允许抽象方法有代码?

Django 查询集单元测试

python - 如何解决 SuspiciousOperation : Invalid HTTP_HOST header error?

django - 如何呈现不在 UL 中的 Django 表单错误?

javascript - 如何制作干净的异步循环?

javascript - Jquery、ajax 和 JSON : Parsing GET response fails, 但只是有时?