使用JSON接口数据预填表单字段失败求助
问题诊断与修复方案
我看了你的代码,核心问题出在$.each循环的逻辑上——你搞混了遍历的键名(i)和对应的值(item),还有嵌套对象(father/mother)的处理方式不对。咱们一步步拆解:
1. 最关键的错误:循环中键值判断颠倒
你写的if (item == "name_and_origin")是完全错误的,因为在$.each(data.results[0], function(i, item)这个循环里:
i代表JSON数据里的键名(比如"name_and_origin"、"ueln")item代表该键对应的值(比如"Oddur frá Selfossi"、"352002987187700")
你应该判断i是否等于目标键名,而不是拿值去对比键名。
2. 嵌套对象(father/mother)的处理错误
当遍历到father或mother时,item是一个完整的子对象(比如{"id":"IS1981157025", "name_and_origin":"Kjarval frá Sauðárkróki"}),你原来写的else if (item.father == "id")完全不成立——此时item就是father对象本身,根本没有item.father这个属性。
修复后的完整脚本
其实没必要用$.each遍历,直接通过对象属性访问更高效清晰:
$(document).on('change', '#wf_id', function() { $.getJSON("http://apis.is/horses?id=" + $("#wf_id").val(), function(data) { const horse = data.results[0]; // 把结果存成变量,代码更易读 // 填充普通字段 $("#wf_name_and_origin").val(horse.name_and_origin); $("#wf_ueln").val(horse.ueln); $("#datepicker_15").val(horse.date_of_birth); $("#wf_color_code").val(horse.color_code); $("#wf_color").val(horse.color); $("#wf_country_located").val(horse.country_located); $("#wf_fate").val(horse.fate); $("#wf_microchip").val(horse.microchip || ''); // 处理null值,避免输入框显示"null" // 填充父马信息(嵌套对象) $("#wf_father_id").val(horse.father.id); $("#wf_father_name_and_origin").val(horse.father.name_and_origin); // 填充母马信息(嵌套对象) $("#wf_mother_id").val(horse.mother.id); $("#wf_mother_name_and_origin").val(horse.mother.name_and_origin); }); });
调试小技巧(帮你以后快速定位问题)
下次遇到类似接口数据不匹配的情况,可以在回调函数里加console.log(data),打开浏览器开发者工具的Console面板,就能直观看到返回的JSON结构,确认你访问的属性是否正确:
$.getJSON("http://apis.is/horses?id=" + $("#wf_id").val(), function(data) { console.log(data); // 查看完整返回数据 // ...其他代码 });
内容的提问来源于stack exchange,提问作者stonyvision
相关产品推荐
相关产品推荐

