【问题标题】:Parsing values from core-response in Polymer从 Polymer 中的核心响应解析值
【发布时间】:2015-05-25 19:38:58
【问题描述】:

我正在使用 Polymer 从 flax/python 后端请求 x 和 y 值,我可以在控制台中读取 XMLHttpResquest 响应的值,但现在我需要将输出转换为一组离散的 x 和y 值(因此它可以被 C3.js 读取 - 一个位于 D3 顶部的图形框架)。

这是我用来获取 XMLHttpResquest 响应的代码:

<paper-button affirmative hover on-tap="{{addNewGraph}}">Submit</paper-button>

Polymer("add-graphItem",{

        addNewGraph: function () {

            var HeaderName = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
            var FunctionName = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
            console.log("The options are " +HeaderName +" and " +FunctionName);

            var params = {};
            if (this.$.graphOptionsLoad.$.headerValue.selectedItem) {
                params['DataHeader'] = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
            }
            if (this.$.graphFunctionsLoad.$.functionValue.selectedItem) {
                params['FunctionName'] = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
            }
            this.$.sendOptions.params = JSON.stringify(params);
            var x = this.$.sendOptions.go();
            // this.$.sendOptions.go();
            console.log(x)

            // var ajax = document.querySelector("sendOptions");

            var results = [];
            this.addEventListener("core-response", 
                function(e) {
                    console.log(x.response);
                }
            );
        }
});

这是console.log(x.response); 的输出示例:

{
  "graph": [
    {
      "Header": "MakeModeChange"
    }, 
    {
      "x": [
        0.0, 
        131.35, 
        26971.3, 
        27044.75, 
        27351.4, 
        27404.483333333334, 
        27419.416666666668, 
        33128.96666666667, 
        33549.13333333333, 
        34049.48333333333, 
        77464.26666666666, 
        77609.71666666666, 
        174171.85, 
        259166.98333333334
      ]
    }, 
    {
      "y": [
        1, 
        2, 
        3, 
        4, 
        5, 
        6, 
        7, 
        8, 
        9, 
        10, 
        11, 
        12, 
        13, 
        14
      ]
    }
  ]
}

最终我需要输出看起来像:

['x', 0.0, 131.35, 26971.3, 27044.75, 27351.4, 27404.483333333334...],
['y', 1, 2, 3, 4, 5, 6]

【问题讨论】:

    标签: javascript d3.js polymer c3.js


    【解决方案1】:

    这是一种快速而肮脏的方法 - 不建议大规模使用,或者如果您不完全信任响应值。同样,很明显,但如果他们的 api/数据结构发生变化,你就是 SOL。

    xArr = JSON.parse(x.response).graph[1].x
    xArr.unshift('x')
    
    yArr = JSON.parse(y.response).graph[2].y
    yArr.unshift('y')
    

    你会得到你需要的两个数组,你可以根据需要组合

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多