当前位置:  开发笔记 > 编程语言 > 正文

我弄乱了JSON对象,数组和字符串

如何解决《我弄乱了JSON对象,数组和字符串》经验,为你挑选了1个好方法。

所以,我正在尝试将数据从php发送到js.

PHP

$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);

JS

balkTypesData = {}; //Outside Ajaxcall

success: function(result){
    balkTypesData = result;
    Console.log(balkTypesData);
}

安慰

[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]

现在,我想搜索我的Json对象?!
我想为"typ:Bas 200*600"找到"viktM"

//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
   if (balkTypesData[i][searchField] == searchVal) {
     weigth = balkTypesData[i]['viktM'];
     console.log(weigth);
   }
}

首先,它是我无法.lengt在"balkTypsData"上使用的接缝.它给了我410次点击.必须是所有人物?

其次,我找不到如何访问我的部分对象.
如果我使用:console.log(balkTypesData[i][searchField]);
我得到:"未定义"
我也试图删除"[i].

那我错过了什么?
温柔我还在学习.



1> Ben..:

看看$.parseJSON()(jQuery)或JSON.parse()(vanilla):

用jQuery

success: function(result){
    balkTypesData = $.parseJSON(result);
    console.log(balkTypesData);
    console.log(balkTypesData[i][searchField]);
}

没有jQuery

success: function(result){
    balkTypesData = JSON.parse(result);
    console.log(balkTypesData);
    console.log(balkTypesData[i][searchField]);
}

推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有