Django Ajax错误 [英] Django ajax error

查看:83
本文介绍了Django Ajax错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting an error while using AJAX to populate a table inside my django template. I am not sure what the error is, please help me in resolving this issue. I have shared all the important files, if I remove ajax and redirect the url to the destination URL then the code works fine, but somehow the ajax implementation is throwing an error.

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

searchtrips.html

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

htmlfile

    <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>

得分成本 行程

Score Cost Itinerary

推荐答案

该错误表示您的视图被挂起或抛出异常.

The error means that your view is hanged or throwing exception.

首先使用ajax,应防止它多次提交:

First in you ajax, you should prevent it submit several times:

$("#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);
        }
    });
});

在您的视图中,下一步,如果有任何可能,您可能想捕获异常:

Next in your view, you might want to catch exception if there is any:

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 ,因为您的代码样式和命名约定非常糟糕.

Also make sure that you read PEP 8 since your code styling and naming convention is quite bad.

希望有帮助.

这篇关于Django Ajax错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆