Django用AJAX传递参数

时间:2011-06-26 15:45:19

标签: django django-views parameter-passing

我正在尝试将参数传递给Django视图,但我无法确定最佳方法是什么。

我正在进行AJAX调用,而我的javascript代码是

url = "/review/flag/code/"+ code +"/type/" + type + "/content/" + content + "/";
$.getJSON(url, somefunction);

此次通话的相应网址

(r'^rate/code/(?P<code>[-\w]+)/type/(?P<type>[-\w]+)/content/(?P<content>[-\w]+)/$', 'project.views.flag_review'),

我可以在我的视图中获取参数

def rate_review(request,code,type,content):
    ....

我的问题是因为content来自textarea,它可能涉及许多转义字符并且像上面那样传递它会导致正则表达式引起的问题。

如果我传递了www.xx.com/review/rate?code=1&type=2&content=sdfafdkaposdfkapskdf等参数,有什么办法吗?

谢谢

2 个答案:

答案 0 :(得分:4)

当然,在您的rate_review功能中,您可以访问request.GET并访问这些参数:

/rate/code/?foo=bar

def rate_review(request):
    request.GET['foo']

答案 1 :(得分:4)

如果content变量是通过表单中的textarea输入字段输入的,那么您应该使用HTTP POST方法来提交数据。你会得到类似的东西:

 url = "/review/flag/code/"+ code +"/type/" + type;
 $.post(url, {'content': content}, somefunction, 'html');

 (r'^rate/code/(?P<code>[-\w]+)/type/(?P<type>[-\w]+)/$', 'project.views.flag_review'),

def rate_review(request,code,type):
    content = request.POST['content']
    ...