weixin_33724046 2020-03-05 02:50 采纳率: 0%
浏览 74

Django,Ajax和GET请求

There are plenty of similar questions here but I can't solve that problem I have. Situation is simple in theory - I send json to Django view, I get a json response. I did it with python, with Django, with REST framework. But with Ajax I can't do it, there's something with URLconf and ajax's relative url kind of stuff and I can't figure out what's wrong and how to make it work. I mean with some URL confs I can send a request with my chrome plugin and I have a response I need, but ajax is getting 404 with that confs. If I change it Django starts to return my html page instead of json response. What am I missing here? My ajax request:

$.ajax({
        url: 'ajax/apply_city/',
        type: 'GET',
        data: {
            'city': obj.textContent
        },
        dataType: 'json',
        success: function(data) {
            var str = '';
            data.districts.forEach(function (district) {
                str += '<a class="dropdown-item" href="#" onclick="applyDistrict(this)">' + district + '</a>';
            });
            window.alert(str);
            document.getElementById("district_dropdown").innerHTML = str;
        },
    });

urls that works with requests from everything but not ajax:

    re_path('^index/$', views.index, name='index'),
    re_path('^index/ajax/apply_city/', views.apply_city, name='apply_city'),

Logs show Not Found: /index/... when ajax makes request and GET /index/... 404. I've seen that for ajax I shouldn't close url with $ sign. If I do ^index/ I get HTML page as a response (but with HTTP200). Maybe that's some Django issue or I don't understand how to do it properly. If anyone knows how to fix it please help.

  • 写回答

1条回答

  • hurriedly% 2020-03-05 03:30
    关注

    It's probably that you put the wrong URL. You can try changing the URL within ajax just like below:

    url: "{% url 'apple_city' %}",
    
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退