jQuery Json对象。每个()循环返回未定义的

jQuery Json对象。每个()循环返回未定义的,jquery,json,ajax,wordpress,Jquery,Json,Ajax,Wordpress,我已经看到过关于这个问题的类似帖子,但还没有找到适合我的解决方案 我的Json在Jsonlint中有效: { "genre": { "id": 44, "text": "Mystery" }, "status": "11 episodes", "director": { "id": [ 83, 84, 85 ],

我已经看到过关于这个问题的类似帖子,但还没有找到适合我的解决方案

我的Json在Jsonlint中有效:

{
    "genre": {
        "id": 44,
        "text": "Mystery"
    },
    "status": "11 episodes",
    "director": {
        "id": [
            83,
            84,
            85
        ],
        "text": [
            "Matsuyama Hiroaki",
            "Aizawa Hideyuki",
            "Mihashi Toshiyuki"
        ]
    }
}
我的ajax调用:

$.ajax({
      url: link, //link to php file
      type: "POST",
      data: postForm,
      dataType  : 'json',
      success: function (data) {
         console.log(data);
         if(data !== "fail"){
             $.each(data.director, function(i, term) {
                $('#acf-field_5dc7e03cd489d').append(new Option(term.text, term.id, true, true)).trigger('change');
             }); // Append options to field in post editor

            $("#get_all").val("Submit");
            $("#get_all").removeAttr('disabled');
         }else{
            alert("fail");
            $("#get_all").val("Submit");
            $("#get_all").removeAttr('disabled');
         }     

      },
      error: function(jqXHR, textStatus, errorThrown) {
         console.log(textStatus, errorThrown);
         $("#get_all").val("Submit");
         $("#get_all").removeAttr('disabled');
      }
  });
它正在创建选项,但为空,控制台显示未定义。

调用对象时,回调的第一个参数是属性名,第二个参数是其值。因此,当您这样做时:

$.each(data.director, function(i, term) {
    $('#acf-field_5dc7e03cd489d').append(new Option(term.text, term.id, true, true)).trigger('change');
});
使用您发布的数据,它将运行两次。在第一次迭代中,
i
将取值
id
term
将取数组
[83,84,85]
。在第二次迭代中,
i
将采用值
text
术语
将采用数组
[“松山广崎”、“爱泽秀幸”、“三桥俊之”]

如果要根据
id
text
添加选项,可以执行以下操作:

data.director.id.forEach(function(id, index) {
    $('#acf-field_5dc7e03cd489d').append(new Option(data.director.text[index], id, true, true)).trigger('change');
}); 
调用对象时,回调的第一个参数是属性名,第二个参数是其值。因此,当您这样做时:

$.each(data.director, function(i, term) {
    $('#acf-field_5dc7e03cd489d').append(new Option(term.text, term.id, true, true)).trigger('change');
});
使用您发布的数据,它将运行两次。在第一次迭代中,
i
将取值
id
term
将取数组
[83,84,85]
。在第二次迭代中,
i
将采用值
text
术语
将采用数组
[“松山广崎”、“爱泽秀幸”、“三桥俊之”]

如果要根据
id
text
添加选项,可以执行以下操作:

data.director.id.forEach(function(id, index) {
    $('#acf-field_5dc7e03cd489d').append(new Option(data.director.text[index], id, true, true)).trigger('change');
}); 

“data.director”不是数组,而是“data.director.id”,因此循环需要在这里进行。下面的更正将有效:)


“data.director”不是数组,而是“data.director.id”,因此循环需要在这里进行。下面的更正将有效:)


我会记住的,谢谢。我会记住的,谢谢。