【问题标题】:Django ajax errorDjango ajax 错误
【发布时间】:2013-08-05 03:23:08
【问题描述】:

我在使用 AJAX 填充 django 模板中的表格时遇到错误。我不确定错误是什么,请帮助我解决此问题。我已经共享了所有重要文件,如果我删除 ajax 并将 url 重定向到目标 URL,那么代码可以正常工作,但是 ajax 实现会以某种方式抛出错误。

Exception happened during processing of request from ('127.0.0.1', 64879)
Traceback (most recent call last):
  File "c:\Python27\Lib\SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "c:\Python27\Lib\SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "c:\Users\mayayadav\djcode\mysite\venv\lib\site-packages\django\core\serv
ers\basehttp.py", line 150, in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "c:\Python27\Lib\SocketServer.py", line 651, in __init__
    self.finish()
  File "c:\Python27\Lib\SocketServer.py", line 710, in finish
    self.wfile.close()
  File "c:\Python27\Lib\socket.py", line 279, in close
    self.flush()
  File "c:\Python27\Lib\socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in yo
ur host machine

Views.py

def SearchTrips(request):
    city=request.POST['city'].replace(" ","%20")
    location=request.POST['location'].replace(" ","%20")
    duration=request.POST['duration']
    print city
    print location
    url="http://blankket-mk8te7kbzv.elasticbeanstalk.com/getroutes?city="+city+"&location="+location+"&duration="+duration
    print url
    x=urllib2.urlopen(url)
    datas=json.load(x)          
    return render(request,'searchtrips.html',{'datas':datas})

Ajax.js

$(function(){

        $("#routes").submit(function() {

             $.ajax({
                    type: "POST",
                    url: '/searchtrips/',
                    data: {
                    'city' : $('#city').val(),
                    'location' : $('#location').val(),
                    'duration' : $('#duration').val(),
                    'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value
                    },                    
                success:searchSuccess,
                datatype: 'html'
                });
    });
});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#routeTable').html(data);
};

searchtrips.html

                    {% for data in datas %}
            <tr>
                            <td>{{ data.score}}</td>
                            {%for element in data.place.elements%}
                            <td>{{element.placeName}} </td>
                            {% endfor %}
            </tr>
                    {% endfor %}

html文件

    <form class="form-search"  action ="" id="routes" method="post" name="routes" align="center">
........................

{% csrf_token %}
<button type="submit" class=""> <i class="icon-search icon-white"></i> Search </button>

</form>

<table class="table table-hover" id="routeTable" style="display:none">
    <thead>
        <tr>

分数成本 行程

【问题讨论】:

    标签: ajax django jquery django-templates


    【解决方案1】:

    我认为问题在于返回函数。当你使用 ajax 时,你不能在 render 中返回它。

    if request.is_ajax():
        return HttpResponse(datas, mimetype="application/javascript")
    else:
        return render(request,'searchtrips.html',{'datas':datas})
    

    【讨论】:

      【解决方案2】:

      错误意味着你的视图被挂起或者抛出异常。

      首先在你的ajax中,你应该防止它多次提交:

      $("#routes").submit(function (e) {
          e.preventDefault();
      
          $.ajax({
              type: "POST",
              url: '/searchtrips/',
              datatype: 'html',
              data: {
                  'city' : $('#city').val(),
                  'location' : $('#location').val(),
                  'duration' : $('#duration').val(),
                  'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
              },                    
              success: function (resp) {
                  console.log('Success');
                  $('#routeTable').html(resp);
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  console.log('Error');
                  console.log(jqXHR);
                  console.log(textStatus);
                  console.log(errorThrown);
              }
          });
      });
      

      接下来在您看来,如果有任何异常,您可能想要捕获异常:

      def SearchTrips(request):
          city = request.POST['city'].replace(" ","%20")
          location = request.POST['location'].replace(" ","%20")
          duration = request.POST['duration']
          url = "http://blankket-mk8te7kbzv.elasticbeanstalk.com/getroutes?city=%s&location=%s&duration=%s" % (city, location, duration)
      
          try:
              resp = urllib2.urlopen(url)
          except:
              resp = None
      
          if resp:
              datas = json.load(resp)
          else:
              datas = None
      
          return render(request, 'searchtrips.html', {'datas': datas})
      

      还要确保您阅读了PEP 8,因为您的代码样式和命名约定非常糟糕。

      希望对你有帮助。

      【讨论】:

      • 我是 python/coding 的新手,这真的很有帮助,我肯定会阅读 PEP 8。但是我尝试了你的建议,现在调用了 ajax 函数。您能否告诉我是否在 HTML 方面也遗漏了任何内容。谢谢!
      • Ajax 成功被称为是一个好兆头,对吧?有什么问题?
      • 对不起,我的意思是 Ajax 函数“没有”被调用
      • 请检查我编辑的答案。再试一次并检查控制台是否有调试消息/错误。控制台是您的朋友。我相信你可以自己调试
      • 谢谢!我的 ajax 出了点问题,我调试并解决了。
      【解决方案3】:

      这是我的新 ajax.js 代码(只是为了关闭这个线程并供任何人将来参考)

      $(function(){
      
          $('#searchtest').click(function() {
      
              $.ajax({
                  type: "POST",
                  url: "/searchtrips/",
                  data: {
                      'city' : $('#city').val(),
                      'location' : $('#location').val(),
                      'duration' : $('#duration').val(),
                      'search_text' : $('#searchtest').val(),
                      'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
                  },
                  success: searchSuccess,
                  dataType: 'html'
              });
      
          });
      
      });
      
      function searchSuccess(data, textStatus, jqXHR)
      {
          $('#search-results').html(data);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-23
        • 2012-05-28
        • 2011-11-30
        • 2011-09-04
        • 2017-12-23
        • 2011-12-08
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        相关资源
        最近更新 更多