gpt4 book ai didi

javascript - 访问json数组元素

转载 作者:行者123 更新时间:2023-12-02 19:55:13 24 4
gpt4 key购买 nike

这可能是非常容易解决的问题。我发布到一个 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
...

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

关于javascript - 访问json数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com