从JSON数组中提取单个变量

extract single variable from JSON array

本文关键字:单个 变量 提取 JSON 数组      更新时间:2023-09-26

我希望我的问题不像我想的那么蠢。

我想从JSONarray中提取单个变量的值。这里是jquery代码

$(document).ready(function(){
    $("#gb_form").submit(function(e){
      e.preventDefault();
      $.post("guestbook1.php",$("#gb_form").serialize(),function(data){
        if(data !== false) {
            var entry = data;
            $('.entries').prepend(entry);           
        }
      });
    });
  });

数据的内容看起来像这样("MyMessage"answers"MyName"是用户以简单形式写入的值):

[{"消息":"MyMessage","名字":"名字"}]

var "entry"应该在末尾给出(或多或少)以下输出:

"Send from - myname -: - mymessage -"

我无法从数据中提取单个数组值。我试过这样做:

var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;

但是这样就得到了"Send from undefined: undefined"

希望你能帮我。

你可以这样做来获取数组的第一项:

var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
样本小提琴

<标题>更新:

,因为您正在使用$。post你需要显式解析响应为json:

$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
        var response = jQuery.parseJSON(data);
        var msg = "Send from"+response [0].name + " "+response [0].message;
        console.log(msg );
      });

访问数组使用[]表示法

使用.符号

访问对象

对于[{JSON_OBJECT}, {JSON_OBJECT}]

如果我们在名为data的变量中拥有上述JSON对象数组,则首先需要访问数组中的特定JSON对象:

data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on

然后访问JSON对象的属性,我们需要这样做:

data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array