【问题标题】:Django: relative url not working with post calls in ajaxDjango:相对 url 不适用于 ajax 中的 post 调用
【发布时间】:2012-06-24 20:36:58
【问题描述】:

我正在尝试将相对 url 与 post ajax 调用一起使用,如下所示:

当前网址路径:

http://localhost:8000/customer/0/location/0/user/0/

我需要切换到不同的目录。

var absolute = "http://localhost:8000/customer/0/location/0/line_group/addLine/2/";//+phone_id;
var relative= "../../line_group/addLine/1"

            $.get(relative,function(data){
            //this works     
            alert(data);
            });

            $.ajax({
            type: "POST",
            url: relative,
            data: "test=test1",
            error:function(data){
            //throws error when using relative path  
            alert('error');
            },
            success:function(data){
            // works fine when using absolute path 
            alert('success');
            }
            });
            //same thing using just post        
            $.post(relative,test,function(data){
            //Error on relative path
            alert(data);
            return false;
            });

对于我的 get 调用,绝对和相对 url,返回数据。

但是对于 POST 调用,当我使用相对 url 时,我得到内部服务器错误。(绝对 URL 工作正常) 我认为这与 CSRF 无关,因为在我看来,我还包括 @csrf_exempt 用于测试目的。 (我在请求中包含了https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

chrome 调试器在 post call 中使用相对 URL 给我以下错误消息。

Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR) http://localhost:8000/customer/0/location/0/line_group/addLine/1

但是,正如您所见,它确实为我提供了我想要访问的完整 url 链接。 而当我直接点击链接时,我会得到页面的数据。

视图真的很简单:

@csrf_exempt
def addNewLine(request, customer_id, location_id, phone_id,**kwargs):
      error_msg = u"No POST data sent."            
      context = {}
      return render_to_response('line_group/mytest.html', context)

任何机构都有任何建议,关于为什么相对 url 路径在 POST 调用中失败? 提前谢谢..

【问题讨论】:

    标签: ajax django django-urls django-csrf


    【解决方案1】:

    如果您有DEBUG=True,则可以在 Chrome 网络部分预览错误说明。

    由于var relative= "../../line_group/addLine/1" 的末尾没有斜线,可能是 CommonMiddleware 重定向了您的请求。如果要保持 URL 不变,请在项目设置中设置 APPEND_SLASH = False

    【讨论】:

    • 感谢您的快速回复。丢失的 / 导致了错误。但我很好奇为什么 Get 请求工作正常??
    • POST 变量不能被重定向到另一个页面。
    猜你喜欢
    • 2016-06-07
    • 2020-06-30
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多