开发者

Loading data into text fields via jQuery/AJAX/JSON

I have this page that has a variable number of text fields, each named item_#### where #### is the ID of the item the text field is representing. I would like to auto-populate these fields with how much of the item is in stock after the user clicks a button. The JSON return wouls look like this: [#### : 45], [#### : 62] (note the lack of item_ in the key开发者_运维问答)

I'm having trouble working my head around how I can load that data into multiple text fields based on the returned results of a php script. I would assume a loop would be in order, however I'm extremely new to Javascript and jQuery, so I'm lost when it comes to loading this content dynamically...


The data format is not clear, but you could do something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Simple JSON</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.20" />
    <script type="text/Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/Javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
    <script type="text/Javascript">
        $(document).ready(function(){
            $('[name="button"]').click(function(){
                $.get('json.php',function(data){
                    data = $.parseJSON(data);
                    $.each(data,function(i,v){                      
                        $('[name="item-'+i+'"]').attr('value',v);
                    });
                });
            });
        });
    </script>
</head>

<body>
    <input name="text-1" />
    <input name="text-4" />
    <input name="button" type="button" value="update" />
</body>

</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜