在Javascript中从Variable打印JSON

时间:2022-12-24 21:46:07

I am attempting to print a JSON that I get like this:

我正在尝试打印我得到的JSON:

jsonfields = $.ajax({
url: "ajax.php?getsensors="+raw.deviceId, 
async: false
}).responseText;

into an ExtJS datastore that looks like this:

进入如下所示的ExtJS数据存储区:

Ext.grid.dummyData = [
    //jsonfields,
    //["ping"],["location"],["death"],["birth"],["DeviceInfo"],
    ['3m Co',71.72,0.02,0.03,'4/2 12:00am', 'Manufacturing'],
    ['Alcoa Inc',29.01,0.42,1.47,'4/1 12:00am', 'Manufacturing'], ...

So when I alert the variable 'jsonfields' it alerts

因此,当我警告变量'jsonfields'时,它会发出警报

["ping"],["location"],["death"],["birth"],["DeviceInfo"]

But it doesn't render to the grid at all, but when I hard-code the line above into the json, it does render. I set my jsonfields var like:

但它根本不会渲染到网格,但是当我将上面的行硬编码到json中时,它会渲染。我设置我的jsonfields var像:

var jsonfields; 

This is the first thing I do in the script tag. I know that the value of it is updated due to the alert. So how is it different from displaying the JSON from a pre-set variable compared to when I hard-code it in?

这是我在脚本标签中做的第一件事。我知道它的价值因警报而更新。那么与我硬编码时相比,它与预设变量显示JSON有何不同?

Thanks!

谢谢!

UPDATES: I can also see the response of the ajax request in the chrome developer tools XHR, it seems to be structured the same: ["ping"],["location"],["death"],["birth"],["DeviceInfo"]

更新:我也可以在chrome开发者工具XHR中看到ajax请求的响应,它看起来结构相同:[“ping”],[“location”],[“death”],[“birth”] ,[“设备信息”]

alert(typeof jsonfields);

Returns "string"

返回“字符串”

1 个解决方案

#1


1  

It would be better to correct the server so it produces valid JSON and then use an Ext.data.JsonStore

最好纠正服务器,以便生成有效的JSON,然后使用Ext.data.JsonStore

If you cannot correct the server here's a very manual solution:

如果您无法更正服务器,这是一个非常手动的解决方案:

jsonfields = Ext.decode('[' + $.ajax({
    url: "ajax.php?getsensors="+raw.deviceId, 
    async: false
}).responseText + ']');

Ext.grid.dummyData = jsonfields.concat([
    ['3m Co',71.72,0.02,0.03,'4/2 12:00am', 'Manufacturing'],
    ['Alcoa Inc',29.01,0.42,1.47,'4/1 12:00am', 'Manufacturing'], ...
]);

#1


1  

It would be better to correct the server so it produces valid JSON and then use an Ext.data.JsonStore

最好纠正服务器,以便生成有效的JSON,然后使用Ext.data.JsonStore

If you cannot correct the server here's a very manual solution:

如果您无法更正服务器,这是一个非常手动的解决方案:

jsonfields = Ext.decode('[' + $.ajax({
    url: "ajax.php?getsensors="+raw.deviceId, 
    async: false
}).responseText + ']');

Ext.grid.dummyData = jsonfields.concat([
    ['3m Co',71.72,0.02,0.03,'4/2 12:00am', 'Manufacturing'],
    ['Alcoa Inc',29.01,0.42,1.47,'4/1 12:00am', 'Manufacturing'], ...
]);