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' %}",
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料