无法使用ajax存储结果

时间:2016-08-15 15:16:13

标签: javascript jquery

我试图使用像这样的ajax获得结果

$('#category').click(function(event) {

  category = $("input[name='category']:checked").data("id");
  var Html = "";

  $.ajax({
    type: "POST",
    data: {
      'csrfmiddlewaretoken': '{{csrf_token}}',
      category: category
    },
    url: "{% url 'data_entry' %}",
    success: function(data) {

      console.log(data);

      $.each(data, function(key, object) {
        $.each(object, function(key, values) {
          Html = "<div><label>" + object + "</label>"
          $.each(values, function(key, value) {
            Html += "<div style='float:left'><input name='" + value + "' type='checkbox' value='" + value + "'><span>" + value + "</span></div>"
          });
        });
      });

      console.log(Html)
      $('#attribute').html(Html)
    },
    error: function(response, error) {}
  });
});

我得到的结果是一个看起来像这样的数组

[Object, Object]
0
:
Object
color
:
Array[3]
0
:
"BLUE"
1
:
"RED"
2
:
"YELLOW"
length
:
3
__proto__
:
Array[0]
__proto__
:
Object
1
:
Object
size
:
Array[6]
0
:
"S"
1
:
"M"
2
:
"L"
3
:
"XL"
4
:
"XXL"
5
:
"XXXL"
length
:
6
__proto__
:
Array[0]
__proto__
:
Object
length
:
2
__proto__
:
Array[0]

我试图循环遍历数组的所有值并将其存储在变量Html中,但它只显示最终的迭代值,即size数组中的值。什么可能是错误的,我该如何解决这个错误。

2 个答案:

答案 0 :(得分:3)

每次执行此操作时,您重置变量:

Html = "<div><label>"+object+"</label>"

所以它只会从(外部)循环的最后一次迭代中获得值。这听起来像意味着追加而不是分配:

Html += "<div><label>"+object+"</label>"

答案 1 :(得分:0)

要将数据用作json,您应该将main.cpp: In instantiation of 'void FakeBoost::fake_cast(T) [with T = N::AC]': main.cpp:19:33: required from here main.cpp:10:22: error: 'fake_operator' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive] fake_operator(t); ~~~~~~~~~~~~~^~~ main.cpp:14:6: note: 'void fake_operator(N::AC)' declared here, later in the translation unit void fake_operator(N::AC ac) { ^~~~~~~~~~~~~ 添加到a​​jax请求

dataType: "json"