gpt4 book ai didi

javascript - JSON 数据到表单字段

转载 作者:行者123 更新时间:2023-11-28 08:41:10 26 4
gpt4 key购买 nike

我是 Javascript 和 Jquery 的新手,所以请原谅我的无知。我正在尝试使用我从在线 .asp 数据库中提取的 JSON 数据,让我的表单字段根据邮政编码自动填充城市和州。我收到了成功的 JSON 响应,其中包含可以在开发工具窗口中查看的数据,但无法让它填充表单上的字段。

我的代码是:

$(function() {

var cache = {};
var container = $("#validate");
var errorDiv = container.find("div.text-error");

/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("City" in data)
{
// Set city and state
container.find("input[name='City']").val(data.City);
container.find("input[name='State']").val(data.State);
}
}

// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();

// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
// Build url
var url = "http://dev.xxx.com/ASPFetchers/GetSPROCAsXML.asp?SPROC=EG_GetZipCodeInfo%20/"+(zipcode)+"/&F=JSON";

// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);

// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;

// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});

我的表单上的标记如下:

    <div id="validate">                                                                             
<label>Zip Code</label>
<input type="text" name="zipcode" id="zipcode" size =" 5" maxlength = "5" />
<div class="text-error"></div>

<label>City</label>
<input type="text" name="City" id="City" />

<label>State</label>
<input type="text" name="State" id="State" />
<script type="text/javascript" src="../zip/includes/zip2.js"></script>
</div>
</div>

我可以在开发工具中查看的 JSON 是(基于邮政编码 06702):

{"items":[{"City":"WATERBURY","County":"NEW%20HAVEN","State":"CT","StateName":"CONNECTICUT","Latitude":"0.7252836","Longitude":"-1.274794"},

任何人都可以帮我解决如何从该字符串中获取信息并将其填充“城市”和“州”字段吗?感谢您的时间和知识。

最佳答案

如果您查看此处发布的数据,您将需要在数据中使用 items 数组。

container.find('input[name="City"]').val(data.items[0].City);
container.find('input[name="State"]').val(data.items[0].StateName);

关于javascript - JSON 数据到表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20480567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com