DjangoAjax错误
使用AJAX在django模板中填充表时出错。我不确定错误是什么,请帮助我解决此问题。我已经共享了所有重要的文件,如果我删除ajax并将url重定向到目标url,那么代码就可以正常工作,但不知何故ajax实现抛出了一个错误DjangoAjax错误,ajax,django,jquery,django-templates,Ajax,Django,Jquery,Django Templates,使用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\Socke
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 %}
{%用于数据%中的数据]
{{data.score}
{data.place.elements%}
{{element.placeName}
{%endfor%}
{%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>
........................
{%csrf_令牌%}
搜寻
得分成本
行程
我认为问题出在返回功能上。使用ajax时,不能在渲染中返回它
if request.is_ajax():
return HttpResponse(datas, mimetype="application/javascript")
else:
return render(request,'searchtrips.html',{'datas':datas})
该错误意味着您的视图被挂起或引发异常 首先,在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})
还要确保您阅读了,因为您的代码样式和命名约定非常糟糕
希望有帮助。这是我的新ajax.js代码(仅用于关闭此线程,供任何人将来参考)
我是python/编码新手,这真的很有帮助,我一定会阅读PEP8。但是我尝试了你的建议,现在ajax函数被调用了。你能告诉我,如果我在HTML方面遗漏了什么吗。谢谢Ajax的成功被称为是一个好兆头,对吗?有什么问题吗?很抱歉,我的意思是Ajax函数“没有”被调用。请检查我编辑的答案。请重试并检查控制台中的调试消息/错误。我是你的朋友。我相信你可以自己调试,谢谢!我的ajax出现了一些问题,我调试并解决了它。
$(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);
}