简体   繁体   English

JSON数据到表单字段

[英]JSON Data into form fields

I'm new to Javascript and Jquery so please excuse my ignorance. 我是Java和Jquery的新手,所以请原谅我的无知。 I'm trying to get my form fields to auto populate city and state based on zip code using JSON data I am pulling from an online .asp database. 我正在尝试获取表单字段,以使用从在线.asp数据库中提取的JSON数据基于邮政编码自动填充城市和州。 I am getting a successful JSON response with data that I can view in my dev tools window, but cannot get it to populate the fields on my form. 我收到了可以在开发工具窗口中查看的数据的JSON成功响应,但无法获取它来填充表单上的字段。

My Code is: 我的代码是:

$(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");
});

My markup on my form is as follows: 我在表单上的标记如下:

    <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>

The JSON I can view in my dev tools is(based on zipcode 06702): 我可以在开发工具中查看的JSON是(基于邮政编码06702):

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

Can anyone help me solve how to get the information from this string and have it populate the "City" and "State" field? 谁能帮助我解决如何从此字符串中获取信息,并将其填充到“城市”和“州”字段中? Thank You for your time and knowledge. 感谢您的时间和知识。

If you look at the data you posted here, you will need to use the items array inside of your data. 如果查看此处发布的数据,则需要使用数据内部的items数组。

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

The object that is returned looks is an array of objects . 返回的对象外观是一个对象数组

So first get the items array and refer the 1st item inside it. 因此,首先获取items数组并引用其中的第一项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM