如何通过 Ajax jQuery 将简单数据发送到 Django 中的 views.py? [英] How to send a simple data by Ajax jQuery to views.py in Django?

查看:37
本文介绍了如何通过 Ajax jQuery 将简单数据发送到 Django 中的 views.py?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Ajax jQuery 将一个简单的数据(一个数字)从 home.html 发送到 views.py 中的一个函数.但似乎没有调用该函数.

I want to send a simple data (a number) from home.html to a function in views.py by using Ajax jQuery. But it seems that the the function is not being called.

home.html:我正确地得到了成功响应.我在成功通知上看到了 tagID.我想在我的 views.py 中看到这一点

home.html: I get the success response correctly. I see the tagID on the success notification. I want to see that in my views.py

...
function GetInfo(e){
                document.getElementById("test3").innerHTML = e.target.myCustomID;
                var tagID = e.target.myCustomID;

        $.ajax({
            url: 'Ajax1',
            type: "POST",
            data: {
                'tagID': tagID,
                'csrfmiddlewaretoken': '{{ csrf_token }}',
            },
            success: function (data) {
                alert ("Congrats! You sent some data: " + tagID);}
            ,
            error: function() {
                 alert ("Something went wrong");
             }
                })};

views.py:我想看到这个函数被ajax调用了.所以如果命令打印(AAAAAAAAAAAAA")有效,我很高兴!

views.py: I want to see that this function is called by the ajax. So if the command print ("AAAAAAAAAAAAA") works, I am happy!

...
@csrf_exempt
def Ajax1(request):
    print ("AAAAAAAAAAAAA")
    if request.is_ajax() and request.POST():
        print("BBBBBBBBBBBBB")
        TagID = request.POST.get('tagID', None)
    else:
        raise Http404

my_app/urls.py

urlpatterns = [
    url(r'', views.home_map, name="home"),
    url(r'^ajax/$', views.Ajax1, name="Ajax")
]

urls.py

urlpatterns = [
    path(r'', include('my_app.urls')),
    path('admin/', admin.site.urls),
    path(r'^ajax/$', Ajax1, name='Ajax')
]

你能告诉我我错过了什么吗?谢谢

would you please let me know what I am missing? thanks

更新

根据善意的建议,我做了一些更改.这仍然不起作用.

Based on the kind suggestions, I made some changes. Still this is not working.

**views.py: **

**views.py: **

def ajax1(request):
    TagIDD = request.POST['object_type']
    print("AAAAAAAAAAAAAAAAA", TagIDD)
    if request.is_ajax() and request.method == "POST":
        print("BBBBBBBBBBBBB")
        TagID = request.POST.get('tagID')
    else:
        raise Http404
    # TagID = request.POST('tagID')
    print ("Hello")
    print(TagID)

    response = {
        'TagID': TagID
    }
    return HttpResponse(response)

home.html

    function GetInfo(e){
                document.getElementById("test3").innerHTML = 
                 e.target.myCustomID;
                const tagID = e.target.myCustomID;

                $.ajax({
                        type: "POST",
                        url: "{{ 'ajax-view/' }}",

                        data: {
                        'csrfmiddlewaretoken': '{{ csrf_token }}',
                        'tagID': tagID
                         },
                        success: function (data) {
                            alert ("Congrats! You sent some data: " + 
                                       tagID);}
                        ,
                        error: function() {
                              alert ("Something went wrong");}
                        })
                };

 </script>

my_app\urls.py:

urlpatterns = [
    url(r'', views.home_map, name="home"),
    url('ajax-view/', views.ajax1, name='ajax-test-view')
]

urls.py:

urlpatterns = [
    path(r'', include('wrms01_map.urls')),
    path('admin/', admin.site.urls),
]

不过,似乎 ajax 并没有调用函数ajax1";在views.py中.但是我可以看到成功通知.提前致谢.

Still, it seems that the ajax is not calling the function "ajax1" in views.py. But I can see the success notification. Thanks in advance.

推荐答案

您正在执行错误的 ajax 调用.您必须在 url 中传递端点的 EXACT URL:''

You are doing the ajax call wrong. You have to pass the EXACT URL of your endpoint inside the url:''

您所做的是传递一个字符串Ajax1",在您的 urls.py 中找不到该字符串.在您的 urls.py 中,您将 'ajax' 作为 url 模式,而 Ajax1 是您的视图函数名称.

What you have done is passing a string 'Ajax1' which inside your urls.py is no where to be found. In you urls.py you have 'ajax' as the url pattern and Ajax1 is your view function name.

此外,我在您的 urls.py 中观察到的 2 种不同视图方法具有相同的模式(这是一种不好的做法).

Also what I observe inside your urls.py you have same patterns for 2 different view methods (this is a bad practise).

现在在你的 ajax 中执行此操作

For now do this inside your ajax

$.ajax({
            url: "{%url 'Ajax'%}",  //This is the jinja template tag that will automatically fill in the url pattern from your urls.py corresponding to the name of that url pattern
            type: "POST",
            data: {
                'tagID': tagID,
                'csrfmiddlewaretoken': '{{ csrf_token }}',
            },
            success: function (data) {
                alert ("Congrats! You sent some data: " + tagID);}
            ,
            error: function() {
                 alert ("Something went wrong");
             }
  })

这篇关于如何通过 Ajax jQuery 将简单数据发送到 Django 中的 views.py?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆