来自django视图的AJAX调用获取请求时出现错误404

时间:2017-02-12 15:24:35

标签: python ajax django get django-views

对于应该从django视图中获取数据的ajax请求,我收到“Page not for error”

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>

projectboard / urls.py         来自django.conf.urls import url,include

    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)

1 个答案:

答案 0 :(得分:0)

好像你的网址模式错了。尝试改变它,如下所示:

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')
]

这有用吗?