“步行" JSON响应并填充表单字段-更有效的方法? [英] "Walk" JSON response and populate form fields -- more efficient approach?
问题描述
我知道有一种更优雅/有效的方法(在php中,我将使用foreach),但是使用jQuery,我该如何遍历JSON响应的var/val对并使用具有相同ID的表单字段填充JSON响应中的字段名称?
I know there is a far more elegant/efficient way of doing this (in php I would use foreach) but with jQuery how can I walk the var/val pairs of a JSON response and populate form fields with the same id's as the field names in the JSON response?
这是我的JSON响应:
Here is my JSON response:
[{"field":"svendor_name","value":"Vendor Name Inc."},{"field":"svendor_addr1","value":"1234 Vendor Lane."},{"field":"svendor_addr2","value":"Suite 100"},{"field":"svendor_city"
,"value":"Vendorville"},{"field":"svendor_state","value":"CA"},{"field":"svendor_zip","value":"90210"},{"field"
:"svendor_phone","value":"800-555-1234"}]
这是我的jQuery代码,用于填充表单:
Here is my jQuery code for populating the form:
$(document).ready(function()
{
$('#svendor_name').bind("change", function()
{
var svendor = $("#svendor_name").val();
svendor = svendor.replace(/&/g, '*');
$.getJSON("get_vendors.php?sname=" + svendor,
function(data)
{
$.each(data,
function(i, item)
{
if(item.field == "svendor_name")
{
$("#svendor_name").val(item.value);
}
else if(item.field == "svendor_addr1")
{
$("#svendor_addr1").val(item.value);
}
else if(item.field == "svendor_addr2")
{
$("#svendor_addr2").val(item.value);
}
else if(item.field == "svendor_city")
{
$("#svendor_city").val(item.value);
}
else if(item.field == "svendor_state")
{
$("#svendor_state").val(item.value);
}
else if(item.field == "svendor_zip")
{
$("#svendor_zip").val(item.value);
}
else if(item.field == "svendor_phone")
{
$("#svendor_phone").val(item.value);
}
else if(item.field == "svendor_id")
{
$("#svendor_id").val(item.value);
}
});
});
});
});
这一切都很好,但是我真的想避免所有的if/else语句,而只是使用从getJSON方法返回的数据来确定哪些字段填充了什么值.什么是更清洁/更有效的方法?
That all works fine and good but I really want to avoid all the if/else statements and just use the data coming back from the getJSON method to determine what fields get populated with what values. What is a cleaner/more effective approach to this?
-尼古拉斯
推荐答案
您可以通过将$ .each替换为以下内容来摆脱所有"if"语句:
You can get rid of all "if" statements by replacing your $.each with this:
$.each(data, function(i, item){
$("#"+item.field).val(item.value);
});
这篇关于“步行" JSON响应并填充表单字段-更有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!