返回数组时解析Ajax响应

时间:2018-10-25 12:06:13

标签: javascript ruby-on-rails arrays ajax

我正在尝试从查询中解析ajax响应,但是,它似乎返回的是数组而不是单个记录。

如何将数组转换为单个响应,然后进行解析,以便我的className={classes.pagination}变量只是响应中的测量数据。

结果

measured

javascript

[
    {
        id: 1,
        company_id: 2,
        weightset_id: 1,
        name: 'A.2000',
        nominal: '2000.0',
        measured: '1999.9998',
        uncertainty: '0.002',
        precedence: 1,
        edited_by: null,
        created_by: 2,
        drift: 2,
        created_at: '2018-09-18T20:00:13.600Z',
        updated_at: '2018-09-18T20:42:31.804Z',
    },
];

2 个答案:

答案 0 :(得分:0)

您可以使用$.getJSON并负责解析结果,您必须使用.json视图来响应json格式

$(".repeatability_weight").on('change', function(){
  /* code code code */

  url = '<%= weightsets_weight_find_path %>';
  data = {weight_id: applied_weight}

  $.getJSON(url, data, function(data) {
    console.log(data) //this should print the array on the console
    var measured = data[0].measured //note the [0], you want the first element of the array to get the `measured` property
    console.log(measured)
  })

  /* the rest of your code */
})

检查文档以获取更多详细信息https://api.jquery.com/jQuery.getJSON/

答案 1 :(得分:-1)

如果服务器以字符串格式返回

kubeadm init --apiserver-advertise-address=198.168.56.101 --pod-network-cidr=192.168.0.0/16

--- Kubeadm init stuck on [init] This might take a minute or longer if the control plane images have to be pulled.

然后使用

'[{"id":1,"company_id":2,"weightset_id":1,"name":"A.2000","nominal":"2000.0","measured":"1999.9998","uncertainty":"0.002","precedence":1,"edited_by":null,"created_by":2,"drift":2,"created_at":"2018-09-18T20:00:13.600Z","updated_at":"2018-09-18T20:42:31.804Z"}]'

如果服务器直接返回数组

var resp = JSON.parse(response);
var measured = resp[0].measured;

那么访问是直接的,您无需再次解析它。

[{"id":1,"company_id":2,"weightset_id":1,"name":"A.2000","nominal":"2000.0","measured":"1999.9998","uncertainty":"0.002","precedence":1,"edited_by":null,"created_by":2,"drift":2,"created_at":"2018-09-18T20:00:13.600Z","updated_at":"2018-09-18T20:42:31.804Z"}]

编辑: 如ADyson所述,服务器始终返回一个字符串。这取决于您的需求以及如何解析数据。如果您已经解析了数据(例如使用jquery时如何设置datatype:json),则可以直接使用它,否则JSON.parse始终存在。