简体   繁体   English

jQuery从json填充表单

[英]jQuery populate form from json

I'm clearly missing something about jquery... I'm trying to populate a form that is inside a jQueryUI dialog box. 我显然错过了关于jquery的一些内容......我正在尝试填充jQueryUI对话框中的表单。 I'm getting the JSON data just fine, but it escapes me how I reference the data and set the value of the form fields... 我收到的JSON数据很好,但它让我无法引用数据并设置表单字段的值...

You will see THREE attempts below - the last one is the one almost everyone says to use - but the form remains BLANK... What am I missing????? 你会看到下面的三个尝试 - 最后一个是几乎每个人都说要使用的 - 但形式仍然是BLANK ...我错过了什么?????

$( '#companies' ).on( 'click', '.uLink' , function( event ) {
    // set ID
    var xid = $( this ).data( 'identity' );
    // get record
    $.ajax({
        type: 'POST',
        url: 'm/company_edit.php',
        dataType: 'json',
        data: { id: xid },
        success: function ( data ) {
            // display dialog
            $( '#company-form-container' ).dialog( 'open' );

            /* ATTEMPT #1 - with a variant on 'name' - form remains blank
            // populate form
            $( '#companyid' ).val( value.id );
            $( '#name' ).val( 'test' + value.name );
            $( '#address1' ).val( value.address1 );
            $( '#address2' ).val( value.address2 );
            $( '#city' ).val( value.city );
            $( '#state' ).val( value.state );
            $( '#postalcode' ).val( value.postalcode );
            $( '#phone' ).val( value.phone );
            $( '#contact' ).val( value.contat );
            $( '#email' ).val( value.email );
            */

            /* ATTEMPT #2 - supposed to make some accommodation for field type...
                            Make assumption that fields are named same as JSON fields, and the you only
                            want to use the data value in that one spot...*/
                           /*
            var frm = '#company-form';
            $.each(data, function( key, value ){
                var $ctrl = $( '[name='+key+']', frm );
                switch( $ctrl.attr( "type" ) )  {  
                    case "text" :   
                    case "hidden":  
                    case "textarea":  
                    $ctrl.val(value);   
                    break;   
                    case "radio" : case "checkbox":   
                    $ctrl.each(function(){ if($(this).attr('value') == value) {  $(this).attr("checked",value); } });
                    break;  
                }  
            });  
            */

            // attempt 3 - still no go
            $.each( data, function( key, value ) {
                $( '#' + key ).val( value ); 
               });

/* // attempt suggested below - no changes... var c = jQuery.parseJSON( data ); / * //尝试在下面建议 - 没有变化...... var c = jQuery.parseJSON(data);

            // populate form
            $( '#companyid' ).val( c.id );
            $( '#name' ).val( c.name );

*/ * /

        },

        error: function () {    
            // there's an error
            $( '#message' ).html( '<p>There was a problem on the server... </p>' );
            $( '#message' ).removeClass( 'hidden' ).addClass( 'message' );
        }
    });

    return false;
});

Sample of JSON data JSON数据的示例

[{"id":"3", "name":"Sub Customer B", "address1":"232 road", "address2":"", "city":"Galatan ", "state":"TN", "phone":"", "email":""}]

and this is the HTML Form 这是HTML表单

<!-- the form -->
<div id="company-form-container" title="Create New Company">
<p class="validateTips">* fields are required.</p> 
<form id="company-form" >
<fieldset>

    <input type="hidden" name="customer_id" id="customer_id" value="" />

    <label for="name">name<sup>*</sup> <span class="fieldhint"></span></label> <br/>
    <input type="text" name="name" id="name" 
           size="50" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="address1">address1 <span class="fieldhint"></span></label> <br/>
    <input type="text" name="address1" id="address1" 
           size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="address2">address2 <span class="fieldhint"></span></label> <br/>
    <input type="text" name="address2" id="address2" 
           size="10" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="city">city <span class="fieldhint"></span></label> <br/>
    <input type="text" name="city" id="city" 
           size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="state">state <span class="fieldhint"></span></label> <br/>
    <input type="text" name="state" id="state" 
           size="5" maxlength="3" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="postalcode">postal code <span class="fieldhint"></span></label> <br/>
    <input type="text" name="postalcode" id="postalcode" 
           size="20" maxlength="15" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="phone">phone <span class="fieldhint"></span></label> <br/>
    <input type="text" name="phone" id="phone" 
           size="20" maxlength="20" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="contact">contact <span class="fieldhint"></span></label> <br/>
    <input type="text" name="contact" id="contact" 
           size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="email">email <span class="fieldhint"></span></label> <br/>
    <input type="text" name="email" id="email" 
           size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

</fieldset>
</form>

myopic coding... brought on by too many little things... 近视编码...由太多小事带来......

the issue was that the form had a field "customer_id" but the JSON was feeding "id"... 问题是该表单有一个字段“customer_id”,但JSON正在输入“id”...

$.each( data, function( key, value ) {
    $( '#' + key ).val( value ); 
});

THIS code did indeed work, once I corrected this error - of course I had to break it out into a separate page and isolate each step in order to see that - however it's give me a little better insight. 这个代码确实有效,一旦我纠正了这个错误 - 当然我不得不把它分解成一个单独的页面并隔离每一步以便看到 - 但是它给了我更好的洞察力。

Thx for the help 谢谢你的帮助

Success function is returning json data into 'data' variable, while you are using 'result' variable in your 3rd attempt. 成功函数将json数据返回到'data'变量,而在第3次尝试中使用'result'变量。

So, Changing "success: function ( data )" line into "success: function ( result )" maybe solve your problem. 因此,将“成功:功能(数据)”行更改为“成功:功能(结果)”可能会解决您的问题。

EDIT 编辑

Check Using, 检查使用,

var c = jQuery.parseJSON( data );
$( '#companyid' ).val( c['id'] );
$( '#name' ).val( c['name'] );

use jQuery.parseJSON() to decode the json encoded data in the method 1. Make sure that you do send json encoded data from your company_edit.php 使用jQuery.parseJSON()解码方法1中的json编码数据。确保从company_edit.php发送json编码数据

For Your Information 供你参考

I guess it would be perfect if you can use a Javascript template engine which will do the trick for you. 我想如果你可以使用一个Javascript模板引擎来完成这个技巧,那将是完美的。 Try one of these with the method one. 使用方法一尝试其中之一。

Good Javascript template engine to work with JSON 使用JSON的好Javascript模板引擎

JSON templating engine JSON模板引擎

What Javascript Template Engines you recommend? 你推荐什么Javascript模板引擎?

http://www.jquery4u.com/javascript/10-javascript-jquery-templates-engines/ http://www.jquery4u.com/javascript/10-javascript-jquery-templates-engines/

您可以使用https://github.com/corinis/jsForm用json填充表单字段(并再次返回)

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

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