访问json数组元素

access json array elements

本文关键字:数组元素 json 访问      更新时间:2023-09-26

这可能是一个非常简单的问题。我发布到一个php页面,该页面返回在数据库中创建的新元素的ID-(通过$.ajax发布)-我已经记录了返回的值。

以下代码是我用来发布的代码

$.ajax({
               type: "POST",
               url: "<?=base_url()?>events/add_tag_js/",
               data: url,
               success: function(html){
                   $("#tag_list").append('<li><span id="" class="tag">'+formvalue+'<span class="remove_tag"><a class="remove_tag_link" href="#">x</a></span></span></li>');
                   $("#add_tag").val('');
                   console.log(html);
               },
               failure: function(){
                    $('.error').show();
                    $("#add_tag").val('');
               }
            });

console.log的返回值为

{"error":false,"msg":"Tag added","id":44}

但当我做alert(html.id)时,我会得到未定义?我需要解析返回的json吗?或者我的json不正确?

也许您没有在服务器端脚本上设置正确的内容类型,所以jQuery不知道这是JSON。因此,可以在服务器脚本上将内容类型设置为application/json,也可以使用dataType参数指示请求中需要JSON

...
type: "POST",
url: "<?=base_url()?>events/add_tag_js/",
data: url,    
dataType: 'json', // indicate that you expect JSON from the server
...

尽管建议您将服务器端脚本设置为正确的内容类型。

尝试告诉它将其作为Json处理,在您的情况下,html是一个String,因此您必须使用var myObj=eval(html);哪个不好

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});