【问题标题】:Django - Ajax: sending url params in dataDjango - Ajax:在数据中发送 url 参数
【发布时间】:2016-08-07 07:50:33
【问题描述】:

我正在尝试通过 Ajax 向 Django 服务器发送“GET”和“POST”请求。 首先,我提供 URLConf:

url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'),

现在,AJAX 部分。以前,我是这样做的(避免在数据中发送参数)

$.ajax({
        type: "GET",
        url: '/write_to_file/' + file_name + '/' + content ,
        data: {},
        success: function(data){ 
            alert ('OK');
        },
        error: function(){
            alert("Could not write to server file " + file_name) 
        }
    }); 

直到某个时刻,我对这种方法感到满意,但现在通过“数据”变量传递文件名和内容对我来说很重要,但由于某种原因,我得到了 404 错误。

$.ajax({
        type: "GET",
        url: '/write_to_file/',
        data: {'file_name':file_name, 'content':content},

        success: function(data){ 
             alert ('OK');
        },
        error: function(){
            alert("Could not write to server file " + file_name) 
        }
    });

服务器端错误:

Not Found: /write_to_file/
[15/Apr/2016 14:03:21] "GET /write_to_file/?file_name=my_file_name&content=my_content HTTP/1.1" 404 6662

客户端错误:

jquery-2.1.1.min.js:4 GET http://127.0.0.1:8000/write_to_file/?file_name=my_file_name&amp;content=my_content 404 (Not Found)

任何想法为什么? ajax 语法有问题还是与 URLConf 有某种关系?

【问题讨论】:

    标签: ajax django get urlconf


    【解决方案1】:
    url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'),
    

    现在错了,您发送帖子请求的网址是:/write_to_file/

    url(r'^write_to_file/$',generalFunctions.write_to_file, name ='write_to_file'),
    

    是你想要的我想!

    【讨论】:

    • 好吧,它不再出现 404 错误,而是我有 505 错误,原因不在视图本身(我在函数的开头放置了一个断点,调试器没有到达那一点)。现在的错误是 TypeError: write_to_file() 恰好需要 3 个参数(1 个给定) [15/Apr/2016 14:20:48] "GET /write_to_file/?file_name=my_file_name&content=my_content HTTP/1.1" 500 16010
    • 这确实应该很明显:如果您不再在 URL 中传递这些值,则需要将它们作为函数的参数删除。
    • 是的,所以如果您定义了 write_to_file 视图,则需要删除除请求之外您可能已声明的任何参数。例如def write_to_file(request, file_name, content): ... 应该变成 def write_to_file(request):...
    • 好吧,对不起,我很愚蠢,但是如果我删除它们,那么我怎样才能从 Django 视图访问我通过 Ajax 数据传递的内容?!
    • (in view) file_name = request.GET.get('file_name'),内容类似,也可以看看 request.GET.getlist()
    猜你喜欢
    • 2020-05-13
    • 2013-06-21
    • 2019-07-20
    • 2020-10-08
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多