【问题标题】:Django/AJAX: Sending and receiving a response with POSTDjango/AJAX:使用 POST 发送和接收响应
【发布时间】: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'>&times;</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


    【解决方案1】:

    您正在遍历 JSON 的 results 值,但正如您从示例输出中看到的那样,没有这样的值。你需要遍历crs.features

    $.each (json.crs.features, function (i, val) {
        name.push(val.properties.name);
        zip.push(val.properties.zip);
    }
    

    【讨论】:

    • 啊!我开始了解它是如何工作的......它现在告诉我Uncaught ReferenceError: crs is not defined。我需要在某处声明吗?
    • 哈。这真的帮助我理解 AJAX 语法!但不幸的是,它又回到了原来的错误。如果我将其删除,则不会出现错误报告。
    【解决方案2】:

    尝试添加:

    dataType:"json",
    

    您的$.ajax 电话。这能解决问题吗?

    【讨论】:

    • 我认为这是迭代的问题。我一直在戳它一段时间。 json.features 返回正确的对象,但我仍然无法深入了解变量。
    • 如果你运行:$.each(json.results, function(i, val) {console.log(val)});,你会得到什么?
    • 我想我终于想通了.. 我以为我很久以前就尝试过的东西,但这次它奏效了。我会发布解决方案。
    【解决方案3】:

    这是最终对我有用的序列:

    $.each (json.features, function (i, val)
        name.push(val.properties.name);
        zip.push(val.properties.zip);
    });
    

    nameziptags 是我的模型列。剩下的就是 Django 的 JSON。我应该指出我在这里使用GeoJSON serializer

    这是我为帮助我可视化 JSON 模式而制作的图表:

    {"type": 
        "FeatureCollection", 
    
        "crs": {
            "type": "name",  
            "properties":  {
                "name": "EPSG:4326" 
            }}, 
    
        "features": [{
                "geometry": null, 
                "properties": {
                    "zip": "19146", 
                    "name": "Jamboree", 
                    "tags": []}, 
                    "type": "Feature"
                }, 
    
                {
                "geometry": null, 
                "properties": {
                    "zip": "19146", 
                    "name": "Party", 
                    "tags": []}, 
                    "type": "Feature"
                }]
    }
    

    感谢大家帮助我学习这个!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2012-01-20
      • 2019-10-12
      • 2014-07-13
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多