简体   繁体   English

JSON对象的访问权限值

[英]Cant access value of JSON object

Im doing a little project with flask. 我正在用烧瓶做一个小项目。 Right now, im trying to add options to a select from a JSON object.Despite being able to insert options, i cant access their value 现在,我试图将选项添加到JSON对象的选择中。尽管能够插入选项,但我无法访问它们的值

This my flask code: 这是我的烧瓶代码:

for dealership in session.query(Dealership).filter_by(ownerID = userId).all():
    dealership_list.append({'Name' : dealership.name})

return jsonify(names = dealership_list)

Ajax code: Ajax代码:

success:function(result){
      $.each(result.names, function(Name, value) {
          $('#dealerships').append($("<option/>", {
              value: Name,
              text: value
          }));
      });
    },

each item in result.names is a dealership (as defined by your view function). result.names中的每个项目都是经销result.names (由您的查看功能定义)。

each dealership is a dict consisting of {"Name":the_name_of_this_dealership} 每个经销商都是由{"Name":the_name_of_this_dealership}组成的字典

so $.each(result.names,function(data){console.log(data)} should print each object which is {"Name":some_dealership_name} 因此$.each(result.names,function(data){console.log(data)}应打印每个对象,这些对象为{"Name":some_dealership_name}

so just change it to 所以只需将其更改为

success:function(result){
  $.each(result.names, function(dealership) {
      $('#dealerships').append($("<option/>", {
          value: dealership.Name,
          text: dealership.Name
      }));
  });
},

- or - - 要么 -

better yet just change your python code to just return a list of names since thats the only data you are using 更好的方法是更改​​python代码以返回名称列表,因为多数民众赞成在使用唯一的数据

dealerships = session.query(Dealership).filter_by(ownerID = userId).all()
names = [dealership.name for dealership in dealerships]
return jsonify(names = names)

and just change your js to 只需将您的js更改为

success:function(result){
  $.each(result.names, function(index,a_dealer_name) {
      $('#dealerships').append($("<option/>", {
          value: a_dealer_name,
          text: a_dealer_name
      }));
  });
}

@JoranBeasley Awesome!I used the second solution, but added/change the following: @JoranBeasley太棒了!我使用了第二个解决方案,但添加/更改了以下内容:

$.each(result.names, function(key,name) {
    $('#dealerships').append($("<option/>", {
        value: name,
        text: name
    }));
});

This because your solution was printing the index instead of value.Thanks for the help! 这是因为您的解决方案正在打印索引而不是值。感谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM