Error Django ajax


Answers

El error significa que su vista está colgada o arrojando una excepción.

Primero en ti, ajax, debes evitar que se presente varias veces:

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

A continuación, en su opinión, es posible que desee detectar excepciones si hay alguna:

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

También asegúrese de leer PEP 8 ya que su estilo de código y convención de nomenclatura es bastante malo.

Espero eso ayude.

Question

Recibo un error al usar AJAX para llenar una tabla dentro de mi plantilla django. No estoy seguro de cuál es el error, ayúdenme a resolver este problema. He compartido todos los archivos importantes, si elimino ajax y redirijo la url a la URL de destino, el código funciona bien, pero de alguna manera la implementación de ajax arroja un 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

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

Costo del Itinerario de Costo




Links