将表单数据转换为JSON的最佳方法

时间:2017-10-02 08:42:30

标签: jquery html json

我必须将数据格式转换为JSON格式才能发送到webAPI。

我有一个从page1调用的popupform:

<form id="popupForm" method="post" class="form-horizontal" action="">
<div class="form-group">
    <label class="col-sm-4 control-label" for="Nome">Nome</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="Nome" name="Nome" placeholder="Nome" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="Cognome">Cognome</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="Cognome" name="Cognome" placeholder="Cognome" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="Operatore">Operatore</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="Operatore" name="Operatore" placeholder="Operatore" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="Username">Username</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="Username" name="Username" placeholder="Username" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="Password">Password</label>
    <div class="col-sm-5">
        <input type="password" class="form-control" id="Password" name="Password" placeholder="Password" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="GruppoDiLavoro">Gruppo Di Lavoro</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="GruppoDiLavoro" name="GruppoDiLavoro" placeholder="GruppoDiLavoro" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="ProfiloFunzionalità">Profilo Funzionalità</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="ProfiloFunzionalità" name="ProfiloFunzionalità" placeholder="ProfiloFunzionalità" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="LivelloDiAccesso">Livello Di Accesso</label>
    <div class="col-sm-5">
        <select class="form-control" id="LivelloDiAccesso" name="LivelloDiAccesso" placeholder="LivelloDiAccesso">
            @*http://formvalidation.io/examples/bootstrap-combobox/*@
            <option value="1">Consultazione</option>
            <option value="2">Ispettore 1° livello</option>
            <option value="3">Ispettore 2° livello</option>
            <option value="4">Tecnico</option>
            <option value="5">Amministratore</option>
        </select>
     </div>
</div>
<div class="form-group">
    <div class="col-sm-5 col-sm-offset-4">
        <div class="checkbox">
            <label>
                <input type="checkbox" id="Attivo" name="Attivo" />Attivo
            </label>
        </div>
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="DataCreazione">Data Creazione</label>
    <div class="col-sm-5">
        <input type="date" class="form-control" id="DataCreazione" name="DataCreazione" placeholder="DataCreazione" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="DataScadenza">Data Scadenza</label>
    <div class="col-sm-5">
        <input type="date" class="form-control" id="DataScadenza" name="DataScadenza" placeholder="DataScadenza" />
    </div>
</div>
<div class="form-group">
    <label class="col-sm-4 control-label" for="Mail">Mail</label>
    <div class="col-sm-5">
        <input type="text" class="form-control" id="Mail" name="Mail" placeholder="Mail" />
    </div>
</div>
<div class="form-group">
    <div class="col-sm-9 col-sm-offset-4">
        <button type="submit" class="btn btn-primary" name="Save" value="Save">Save</button>
    </div>
</div>

page1有这段代码:

            function OpenPopup(pageUrl) {
            //alert(localStorage.getItem("UtenteIndex"));
            var $pageContent = $('<div/>');
            //$pageContent.load(pageUrl);
            $pageContent.load(pageUrl, function () {
                $('#popupForm', $pageContent).removeData('validator');
                $('#popupForm', $pageContent).removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse('form');

            });
            $dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
                .html($pageContent)
                .dialog({
                    draggable: true,
                    autoOpen: false,
                    resizable: false,
                    model: true,
                    title: 'Edita Utente',
                    height: 650,
                    width: 900,
                    close: function () {
                        $dialog.dialog('destroy').remove();
                    }
                })


            $('.popupWindow').on('submit', '#popupForm', function (e) {
                var url = $('#popupForm')[0].action;
                //alert($('#popupForm').serialize())
                $.ajax({
                    type: "POST",
                    url: url,
                    data: $('#popupForm').serialize,
                    success: function (data) {
                        if (data.status) {
                            $dialog.dialog('close');
                            oTable.ajax.reload();
                        }
                        alert(url);
                        alert(JSON.stringify(data));
                    },
                    error: function (xhr, status, error) {
                        $dialog.dialog('close');
                        alert(xhr.responseText);
                    }
                })

                e.preventDefault();
            })
            $dialog.dialog('open');
        }

输出JSON不正确。代码返回如下字符串:

  

!DOCTYPE html&gt; \ r \ n \ r \ n \ r \ n meta http-equiv = \&#34; Content-Type \&#34;   含量= \&#34; text / html的; charset = utf-8 \&#34; / \ r \ n \ r \ n   个用户\ r \ n ....

仅对输入数据进行stringfy的最佳方法是什么? 我哪里错了?

2 个答案:

答案 0 :(得分:0)

我个人使用这个jquery片段:

data = $('#myForm').serializeObject();

它会将您的Form序列化为一个对象,其中name属性是属性,值是值,使用它如:

public class MainActivity extends AppCompatActivity {

    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView webView = new WebView(this);
        webView.setClickable(true);
        webView.setFocusableInTouchMode(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.google.com");
        WebClientClass webViewClient = new WebClientClass();
        webView.setWebViewClient(webViewClient);

        setContentView(webView);
        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Please wait");
        pd.setMessage("Page is loading..");
        pd.show();
    }

    public class WebClientClass extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);


        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pd.dismiss();
        }
    }

}

答案 1 :(得分:0)

你有没有试过你的功能:

$('.popupWindow').on('submit', '#popupForm', function (e) .....

这一行之后?

$dialog.dialog('open');

我认为在调用$ dialog.dialog('open')后,弹出窗口的HTML会添加到DOM中;

因此,与弹出窗口标记关联的每个事件都需要在添加到DOM后进行连接