【问题标题】:Error 404 on get request from AJAX call on django views从 django 视图上的 AJAX 调用获取请求时出现错误 404
【发布时间】:2017-06-30 13:44:11
【问题描述】:

对于应该从 django 视图中获取数据的 ajax 请求,我收到“页面不出错”

Projectboard/dashboard.html

 <form action="view">
    <br>
Select your favorite fruit:
<select id="mySelect">
  <option value="apple" selected >Select fruit</option>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>
</form>

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#mySelect").change(function(){
        selected ="apple";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '/projectboard/view/',
            data: {
                   'fruit': selected
                  },
            success: function(result) {
                    document.write(result)
                    }
    });
  });
});
</script>

项目板/urls.py from django.conf.urls 导入url,包含

    from . import views

    urlpatterns = [

url(r'^disp.html$', views.index2, name='index2'),
url(r'^view/(?P<id_remedio>\w+)/$', views.view, name='view'),
url(r'view$', views.view, name='view')
]

views.py

    from django.http import HttpResponse


    def view(request):
    data="bleh"
    if request.method == 'GET':
      print (request.body)
     data = request.body
    return HttpResponse(json.dumps(data))

我得到的错误是

GET http://127.0.0.1:8000/projectboard/view/?fruit=apple 404 (Not Found)

【问题讨论】:

  • 你能从浏览器http://127.0.0.1:8000/projectboard/view/?fruit=apple打开这是网址吗?
  • 没有。它说找不到页面。但是我已经在 projectboard/urls.py 中指定了 url

标签: python ajax django get django-views


【解决方案1】:

您的网址格式似乎是错误的。尝试将其更改为以下内容:

from . import views

urlpatterns = [
   url(r'^disp.html$', views.index2, name='index2'),
   url(r'^view/(?P<id_remedio>\w+)/$', views.view, name='view'),
   url(r'^view/$', views.view, name='view')
]

这行得通吗?

【讨论】:

  • 现在是TypeError at /projectboard/view/ b'' is not JSON serializable
  • 至少现在是到达视图,但看起来没有获取数据。我不知道你的观点到底想做什么。但是要获取'fruit'参数。试试这个:` def view(request): if request.method == 'GET':fruit = request.GET.get('fruit') print 'the fruit is %s' % fruit return HttpResponse(json.dumps(fuit ))` 现在由您来正确处理数据和响应:)
猜你喜欢
  • 2013-02-15
  • 2018-10-30
  • 2010-11-05
  • 2016-01-06
  • 2018-02-03
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多