DragonWar% 2016-09-12 10:15 采纳率: 0%
浏览 70

Django:AJAX和路径参数

I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.

Say we have an url with a path param that maps to a particular view:

url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'))

And then the post.html includes a script that performs an AJAX request to fetch the post as JSON:

post.html

<script src="{{ STATIC_URL }}/js/post.js"></script>
<div id="post-container"></div>

This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner.

post.js

$.ajax({
   url: '/post/??post_id??',
   contentType: 'application/json'
})
.done(function(post_data) {
    togglePlugin(post_data);
});

My main concern is how to figure out what post_id is from the js file in order to make the appropriate call.

How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax.

  • 写回答

2条回答 默认 最新

  • 妄徒之命 2016-09-12 10:23
    关注

    You can pass a post_id variable to django template. However if you don't want it to "hurt", put your .js code (script) in you html file, rendered by django. So you can use django template tags.

    For example:

            var url = "/post/{{post_id}}";
             $.ajax({
                type: 'POST',
                url: url,
                dataType: 'json',
                data: {
                    some_field: field_data,
                    some_other_field: field_data
                },
                success: function(data) {
                    do_something();
                },
                error: function(data) {
                    do_somethin();
                }
            });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么