简体   繁体   English

AJAX数据被发送到错误的Django视图

[英]AJAX data being sent to the wrong Django view

I'm new to django and ajax so I've been working on a project to learn it. 我是django和ajax的新手,所以我一直在研究一个项目。 I have two buttons, one that adds a marker and one that deletes a marker. 我有两个按钮,一个按钮添加一个标记,另一个按钮删除一个标记。

Here is the views.py 这是views.py

@csrf_exempt
def save(request):
    searchVar = request.POST.getlist('search[]')
    waypoint = Waypoint()
    waypoint.name = searchVar[0]
    waypoint.geometry = ('POINT(' + searchVar[2] + " " + searchVar[1] + ')')
    waypoint.save()
    return HttpResponse(json.dumps(dict(isOk=1)), content_type='application/json')

@csrf_exempt
def remove(request):
    objectID = request.POST.get('id')
    point = get_object_or_404(Point, pk = objectID)
    point.delete()

Here is the urls.py 这是urls.py

from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'', 'save', name='waypoints-save'),
    url(r'', 'remove', name='waypoints-remove'),
)

and here is the ajax from the js file 这是js文件中的ajax

    $('#saveWaypoints').click(function () {
    var searchList = [search.name, search.geometry.location.lat(), search.geometry.location.lng()]
    $.ajax({
      url : "waypoints-save",
      type : "POST",
      data : { search : searchList }
    }, function (data) {
        if (data.isOk) {
            $('#saveWaypoints');
        } else {
            alert(data.message);
        }
    });
});
$('#removeWaypoints').click(function () {
  console.log(markerID);
    $.ajax({
      url : "waypoints-remove",
      type : "POST",
      data : { id : markerID }
    }, function (data) {
        if (data.isOk) {
            $('#removeWaypoints');
        } else {
            alert(data.message);
        }
    });
});

The save button works fine, but when I click on the remove button I get this error in my console log 保存按钮可以正常工作,但是当我单击删除按钮时,我在控制台日志中收到此错误

POST http://127.0.0.1:8000/waypoints-remove 500 (Internal Server Error)

IndexError at /waypoints-remove
list index out of range

Request Method: POST
Request URL: http://127.0.0.1:8000/waypoints-remove

and this error in my server cmd 而我的服务器cmd中的此错误

Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range
2017-01-09 22:40:11,781 - ERROR - Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range

Which leads me to believe that the data from the remove button ajax call is being sent to my save view, does anyone know one? 这使我相信,来自remove按钮ajax调用的数据已发送到我的保存视图,有人知道吗?

You have your urls.py file set up wrong. 您的urls.py文件设置错误。 The first parameter is a regular expression to match a URL, so ^$ will match the root path. 第一个参数是匹配URL的正则表达式,因此^$将匹配根路径。 The name parameter is for getting the URL for a specific view, eg when you use the reverse function. name参数用于获取特定视图的URL,例如,当您使用reverse功能时。

^ indicates the beginning of a line and $ indicates the end of a line. ^表示行的开头, $表示行的结尾。 Together, with nothing in between, it will match an empty line. 两者之间没有任何东西,它将匹配一条空行。

To match another URL, such as /waypoints-save/ , you would need to write another regex: ^/waypoints-save/$ . 要匹配另一个URL,例如/waypoints-save/ ,您需要编写另一个正则表达式: ^/waypoints-save/$ This will match the beginning of the line, followed by the characters /waypoints-save/ , followed by the end of the line. 这将匹配行的开头,然后是字符/waypoints-save/ ,然后是行的末尾。 To get your entire urls.py set up correctly, it should look like this: 要正确设置整个urls.py ,应如下所示:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'^/waypoints-save/$', 'save', name='waypoints-save'),
    url(r'^/waypoints-remove/$', 'remove', name='waypoints-remove'),
)

You have defined two URL entries that have the same regex. 您已经定义了两个具有相同正则表达式的URL条目。

url(r'', 'save', name='waypoints-save'),
url(r'', 'remove', name='waypoints-remove'),

Since /waypoints-remove would match r'' (a regex with nothing in it, therefore it will match anything), the first match wins, and the save method is executed. 由于/waypoints-remove将匹配r'' (其中不包含任何正则表达式,因此它将匹配任何内容),因此第一个匹配获胜,并执行save方法。 So the method you expected to run, remove , is not being run. 因此,您期望运行的方法remove不会被运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM