【问题标题】:referring to specific parts of a python dictionary in javascript在 javascript 中引用 python 字典的特定部分
【发布时间】:2013-07-24 16:14:44
【问题描述】:

我做了一个程序来解析数据,然后用它做一个 python json.dumps()。接下来,在我的 javascript 中,我用这个数据做了一个 jQuery getJSON()。 在我用我的数据做json.dumps()之前,我把它分成三个列表,因为我不知道如何处理js中的数据。数据结构如下:

Key: (value1, value2)

我只需要分别在我的 javascript 中引用这些单独的“列”。我觉得用python字典做dumps()可能更有效,但我不知道如何在javascript中引用它。显然,数据保持“分组”很重要

我该怎么做呢?

【问题讨论】:

  • 您能否提供更详细的示例来说明您正在转储的数据以及您希望如何在 javascript 中引用?
  • 听起来你知道该怎么做,你只需要阅读如何访问 JSON 中的值。

标签: javascript python python-2.7 flask


【解决方案1】:

这是我在地图项目中使用的完整示例。 Javascript 通过 Ajax 从烧瓶应用程序加载数据。

JQuery ajax 方法与 getJSON 方法非常相似。

#ajax method to retreive well data for dynamic well values, x_pos, y_pos, substance concentration
@app.route('/getWellData', methods=['GET', 'POST'])
def getWellData():
    #get all samples with that date
    date_collected = request.args.get('date_collected')
    site_id = request.args.get('site_id')
    site_map_id = request.args.get('site_map_id')
    substance_id = request.args.get('substance_id')

    well_results = wellSubstanceDataBySite(
        site_id=site_id,
        site_map_id=site_map_id,
        date_collected=date_collected,
        substance_id=substance_id)

    #return json to updateMarks ajax javascript function
    return json.dumps(well_results)

Javascript:

//call the ajax endpoint for getWellData to return position, values, etc
$.ajax({
    dataType: "json",
    url: '/getWellData',
    data: data,
    success: function(data){

        //iterate over each value in the data array and append it as div element to the .landmarks div
        $.each(data, function(well_id, well){

            //create the mark element, must be all mashed into one line, wont work with multiple lines
            //sutract depth_of_water (well.value) from well.top_of_casing
            var goundwater_elevation_val = well.top_of_casing - well.value
            var mark = '<div class="item mark" id="well-' + well_id + '" data-id="' + well_id + '" data-position="' + well.xpos + "," + well.ypos + '" data-value="' + goundwater_elevation_val.toFixed(4) + '" data-show-at-zoom="0"><div><div class="text"><input class="well-checkboxes" type="checkbox" name="enable-well-' + well_id + '" checked style="margin:3px;"><strong>' + goundwater_elevation_val.toFixed(4) + '</strong></div><img src="/static/jquery-image-viewer/example/images/mark.png" width="50px" height="50px" alt="Permanent Mark" /></div></div>';
            if (well.value != 0) {
                //append the new mark to the .landmarks div
                $('.landmarks').append(mark);
            }

        });

        //refresh all landmarks to plot the new landmarks on the map with the smoothZoom API
        $('#sitemap').smoothZoom('refreshAllLandmarks');
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-16
    • 2021-09-02
    • 1970-01-01
    • 2015-04-14
    • 2018-08-12
    • 2017-12-22
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多