如何将javascript变量值传递给Django中的views.py函数? [英] how to pass javascript variable value to views.py function in django?

查看:279
本文介绍了如何将javascript变量值传递给Django中的views.py函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将从html页面中的javascript标记生成的字符串发送到views.py函数.我将使用该值将其呈现到另一个html页面,另一个javascript将使用它.

I am trying to send a string generated from javascript tag in my html page to views.py function. I'll use that value to render it to another html page where another javascript will use it.

这是解析json数据的变量:

This is the variable which parses json data:

var url = data.result.docs[i].source.enriched.url.url;

我想在views.py中向函数发送"url",但是我找不到解决方法.

I want to send "url" to my function in views.py but i am not able to figure out a way.

我还想保留一个链接,以便当用户单击它时,"URL"将传递给views.py,而我的函数会将其发送到其他html文件.

Also i want to keep a link, so that when user click it the "url" is passed to views.py and my function there send it to other html file.

sjd += "<br/>" + data.result.docs[i].source.enriched.url.title +
            '<a href="/rawHtmlText/url">' + ' Read more' + '</a>' + '<br>'

这是我想在我的页面中建立的链接. 我知道urls.py应该有适当的格式,但我无法弄清楚.

This is kind of link i would like to have in my page. I know urls.py should have a proper pattern, but i am not able to figure it out.

也许可以使用jQuery,但我是该领域的菜鸟,所以卡在这里.

May be jQuery can be used but I am a noob in this field so kind of stuck here.

请指导我.

推荐答案

最简单的方法可能只是构建一个AJAX查询.尝试这样的事情:

The easiest way is probably to just build an AJAX query. Try something like this:

<script type="text/javascript">
    $(document).ready(function() {
        var url = data.result.docs[i].source.enriched.url.url;
        $("#send-my-url-to-django-button").click(function() {
            $.ajax({
                url: "/process_url_from_client",
                type: "POST",
                dataType: "json",
                data: {
                    url: url,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                    },
                success : function(json) {
                    alert("Successfully sent the URL to Django");
                },
                error : function(xhr,errmsg,err) {
                    alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
                }
            });
        });
    });
</script>

假设您的页面上有一个这样的按钮:

Assuming you have a button on your page like this:

<button type="button" id="send-my-url-to-django-button">Send URL to Django View</button>

单击该按钮应将url发送到您的Django视图.然后在Django端,您可以像这样访问url:

Clicking that button should send the url to your Django view. Then on the Django side, you can access the url like so:

def process_url_from_client(request):
    url = request.POST.get('url')

这篇关于如何将javascript变量值传递给Django中的views.py函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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