【发布时间】:2015-09-13 12:03:49
【问题描述】:
今晚我第一次修改 Javascript/JQuery、AJAX、JSON 和 GeoDjango,我都搞混了!
到目前为止,我已经能够通过 POST 请求从 AJAX 成功提交搜索查询,在 Django 中执行搜索,然后将序列化数据传递回 AJAX。但是,我无法弄清楚如何使用 AJAX 再次对其进行解码!
我收到此错误:(Uncaught TypeError: Cannot read property 'length' of undefined)
当我添加以下尝试对数据做某事时:
$.each (json.results, function (i, val) {
//Loop through each returned item and push onto name
name.push(val.id);
//Loop through each returned item and push name onto var zip
zip.push(val.name);
});
我认为这是相关的 Ajax:
var name = [];
var zip = [];
...
//Grab form data
// Submit on submit
$('#event_form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!"); // sanity check
search_zip();
//define and set variables
var searchForm = $("#event_form").val();
return false;
});
// AJAX for submitting search query
function search_zip() {
console.log("event form functional"); // sanity check
$.ajax({
url : "/discover/",
type : "POST", //http method
data : { event_search : $('#search_box').val() }, // data sent with POST request
// handle a successful response
success : function(json) {
$('#search_box').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
console.log("success"); // another sanity check
$.each (json.results, function (i, val) {
//Loop through each returned item and push onto name
name.push(val.name);
//Loop through each returned item and push name onto var zip
zip.push(val.zip);
});
console.log(name);
console.log(zip);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}});
}
我的看法以防万一:
from django.shortcuts import HttpResponse
from django.views.generic import TemplateView
from django.core.serializers import serialize
from AlmondKing.Events.models import Event
from django.core.exceptions import SuspiciousOperation
class MapView(TemplateView):
template_name = "index2.html"
def post(self, request, *args, **kwargs):
if request.POST['event_search']:
self.object = Event.objects.search(request.POST['event_search'])
return HttpResponse(serialize('geojson',self.object), content_type="application/json")
else:
raise SuspiciousOperation("Blank Request Received")
样本输出:
b'{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"properties": {"tags": [], "name": "Party", "zip": "19146"}, "geometry": null, "type": "Feature"}, {"properties": {"tags": [], "name": "Jamboree", "zip": "19146"}, "geometry": null, "type": "Feature"}]}'
我对如何帮助 AJAX 理解数据感到困惑。我正在使用 POST,以便我可以在基于类的 TemplateView 中执行一个函数。但是,似乎 POST 的 AJAX 设置在破译序列化响应方面效果不佳。如何通过一个请求完成所有这些操作?
【问题讨论】:
标签: python json ajax django django-views