【问题标题】:Django Ajax Post Request IssueDjango Ajax 发布请求问题
【发布时间】:2014-05-14 01:35:27
【问题描述】:

我正在使用 Ajax 向 Django 发送 POST 请求。

这是我的 ajax 代码:

$("#submitdata").click(function(){
values = {
"tmode": tmode,
"fmode": fmode,
"t_cool": t_cool,
"t_heat": t_heat,
"hold": hold
};
var jsonText = JSON.stringify(values);
$.ajax({
    url: "/submitdata/",
    type: 'POST',
    data: jsonText,
    dataType: 'json',
    success:function(data){
        alert("Inside success function");
        alert(data.tmode);
    },
    /*complete:function(){
        console.log('complete');
    },*/
    error:function(){
        alert("error");        }
});       });

这是我的看法:

@login_required
def submitvalues(request):
#context = RequestContext(request)
if request.POST:
    jsonvalues = json.loads(request.raw_post_data)
    print json.dumps(jsonvalues)
    #temp = jsonvalues["temp"]
    tmode = jsonvalues['tmode']
    fmode = jsonvalues['fmode']
    t_cool = '65'
    t_heat = '75'
    hold = jsonvalues['hold']
    if jsonvalues.__contains__('t_cool')>=1:
        t_cool = jsonvalues['t_cool']
    if jsonvalues.__contains__('t_heat')>=1:
        t_heat = jsonvalues['t_heat']
    jsonresult = {
                      'tmode':tmode,
                      'fmode':fmode,
                      't_cool':t_cool,
                      't_heat':t_heat,
                      'hold':hold,
                      }
    '''return render_to_response('wifithermostat_3m50/wifithermo3m50.html',
        {'tmode':tmode,'fmode':fmode,'t_cool':t_cool,'t_heat':t_heat,'hold':hold,
         },
        context)'''
    if request.is_ajax()== True:
        return HttpResponse(json.dumps(jsonresult),mimetype='application/json')

我得到了我认为的价值观。但是响应没有成功。我只是想从本质上取回相同的数据。但我没有看到任何成功消息。你能指导我哪里出错了吗?

首先,即使在访问视图函数之前,ajax 函数的错误部分的警报消息也会弹出。此外,它永远不会到达 ajax 调用的成功部分。

我在运行服务器控制台中遇到了 Broken Pipe Error。

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 284, in  run
self.finish_response()
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 324, in finish_response
self.write(data)
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 403, in write
self.send_headers()
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 467, in send_headers
self.send_preamble()
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 385, in send_preamble
'Date: %s\r\n' % http_date()
File "/usr/lib/python2.7/socket.py", line 324, in write
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

如果我没有在 .click(function() {}); 中定义它,这个 ajax 调用可以正常工作 我正在发送带有正常点击功能的 POST 请求。为什么我不能在 click 属性中做呢?

【问题讨论】:

  • 您遇到了什么错误?在runserver 命令的输出中查找 django 错误,或者在浏览器的 javascript 控制台中查找 javascript 错误。
  • @SohanJain:我已经编辑了问题,出现了错误。很高兴您能帮助解决这个问题。我是 Django 新手,很难纠正这个问题。
  • 服务器中的管道损坏消息通常可以忽略。只需杀死服务器并重新启动它。如果您在服务器实际被击中之前遇到错误(验证在您的 runserver 输出中没有调用 /submitdata/),那么问题可能出在 javascript 端。像这样修改你的错误回调:error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); } 这样你就可以打印出你的实际错误是什么。请注意,使用 console.log 比使用警报更容易。 (如果使用 Chrome 调出控制台,请按 f12)
  • 尝试了控制台日志记录。它只是说'error',针对textStatus,errorThrown是一个空字符串,而jqXHR是一堆函数。
  • 这听起来像是一个 JS 问题,因为你说它甚至在调用视图之前就弹出错误。

标签: jquery ajax django


【解决方案1】:

如果您的按钮是例如在表单中,默认操作将是重新加载页面,这将中断帖子,从而给您一个损坏的管道。
通过添加 preventDefault 可以防止重新加载。

【讨论】:

    【解决方案2】:

    @jerry-meng :它不适用于任何触发事件。我不知道为什么。

    但我的问题的解决方案是防止在按下按钮时发生默认操作。

    修改代码:

    $( "#submitthermostatdata" ).click(function(evt) {
    evt.preventDefault();
    values = {
            "tmode": tmode,
            "fmode": fmode,
            "t_cool": t_cool,
            "t_heat": t_heat,
            "hold": hold
            };
    var jsonText = JSON.stringify(values);
    console.log(jsonText);
    $.ajax({
          url : '/submitdata3m50/',
          type: 'POST',
          data: jsonText,
          dataType: 'json',
          success : function(data) {
            var testinggg = $.parseJSON(data.tmode);
            alert(testinggg);
            alert("testing");
          },
          error: function(data) {
            alert("something really wrong");
          }
         }); });
    

    【讨论】:

    • 对于绑定这个功能的按钮,你上面有type = 'submit'吗?如果是,使用 evt.preventDefault() 可能是合理的,但我不明白为什么它对 div 不起作用。无论如何,只要你有修复,现在就足够了。
    • 我最初将“提交”作为按钮类型,但后来将其更改为“按钮”类型。我不确定为什么 preventDefault() 可以作为解决方案!在过去的 3 个小时里,我对这个问题感到困惑。很高兴知道一个原因!
    猜你喜欢
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多