如何AJAX到HTTP请求JSON预先填充Web表单?

时间:2023-01-06 10:28:45

Okay, using Scala Play Framework I have an Action method in my Application Controller that accesses a database for a specific serial and sends a JSON object using Ok(json), which can be accessed through the route GET /json/:serial controllers.Application.getData(serial: String). This part works; I am able to retrieve a unformatted JSON objects for specific serial numbers going directly through localhost/json/serial#.

好的,使用Scala Play Framework我在我的应用程序控制器中有一个Action方法,它访问特定串行的数据库并使用Ok(json)发送JSON对象,可以通过路由GET / json /:serial controllers.Application访问.getData(serial:String)。这部分有效;我能够直接通过localhost / json / serial#检索特定序列号的未格式化JSON对象。

In my views, there is a page for editing this database information. There is an HTML select drop down with a list of serial numbers, and when one of them is selected I'd like to send an AJAX request with that serial number to /json/### and get a JSON object in return. Once I have the JSON object, the forms should be populated with that information so the users know what they are editing.

在我的视图中,有一个用于编辑此数据库信息的页面。有一个带有序列号列表的HTML选择下拉列表,当选择其中一个序列号时,我想将带有该序列号的AJAX请求发送到/ json / ###并获得一个JSON对象作为回报。一旦我拥有了JSON对象,就应该使用该信息填充表单,以便用户知道他们正在编辑什么。

So essentially my question is how can I use AJAX/jQuery to request a JSON object over HTTP (using route /json/:serial) so that I can populate an HTML form with the various fields in the JSON object when a serial is selected from a drop down?

所以基本上我的问题是我如何使用AJAX / jQuery通过HTTP请求一个JSON对象(使用route / json /:serial),以便我可以在从JSON对象中的各个字段填充HTML表单时从下拉?

Let me know if anything is unclear or too ambiguous! Thanks

如果有什么不清楚或太模糊,请告诉我!谢谢

EDIT: Some Code:

编辑:一些代码:

val getData(serial: String) = Action {

val scInfo = *some database query*
val ctrlInfo = *another database query*
val json: JsValue = Json.obj(
        "name" -> scInfo(0)._1,
        "notes" -> scInfo(0)._2,
        "ctrl1" -> Json.obj("name" -> scInfo(0)._3,
            "port" -> scInfo(0)._4,
            "apc" -> scInfo(0)._5),
        "ctrl2" -> Json.obj("name" -> ctrlInfo(0)._1,
            "port" -> ctrlInfo(0)._2,
            "apc" -> ctrlInfo(0)._3),
        "rack" -> scInfo(0)._6,
        "comtrol" -> scInfo(0)._7
    )

    Ok(json)
}

This is a picture of what the form will roughly look like (I figured seeing the actual page was easier than reading the markup)

这是一张大致形状的图片(我认为看到实际页面比阅读标记更容易)

如何AJAX到HTTP请求JSON预先填充Web表单?

So when a Storage Center is selected, that number is sent via AJAX to /json/:serial and should request a JSON object as a result, which will then populate the other fields in the form.

因此,当选择Storage Center时,该号码将通过AJAX发送到/ json /:serial,并应该请求一个JSON对象,然后填充表单中的其他字段。

EDIT 2:

编辑2:

Here's the markup for the view. It's using the Play template engine so anything with a @ in front of it is just scala-code generating markup.

这是视图的标记。它正在使用Play模板引擎,因此前面带有@的任何内容都只是scala-code生成标记。

<div class="header-wrapper">
        <h2 class="header">Edit Information for...</h2>
    </div>

    <div class="sc-content">
    <form class="form-horizontal col-md-12" role="form">
        <div class="form-group">
            <label for="inputSC" class="control-label">Storage Center</label><br>
            <div class="col-sm-6">
                <select class="form-control" onfocus="this.blur()" id="inputSC" placeholder=" ">
                    @storageCenters.map { sc =>
                    <option id="selectSC@sc._1">@{sc._1.replace('-', '/')}</option>
                    }
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="inputRack" class="control-label">Rack</label><br>
            <div class="col-sm-6">
                <select class="form-control" onfocus="this.blur()" id="inputRack" placeholder=" ">
                    @racks.map { rack =>
                    <option id="selectRack@rack.name">@rack.name</option>
                    }
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="inputConsoleIP" class="control-label">Console IP/Port</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputConsoleIP" placeholder="i.e. 127.0.0.1">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputPort" placeholder="i.e. 00000">
            </div>
        </div>
        <div class="form-group">
            <label for="inputAPC" class="control-label">APC Outlet</label><br>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="inputAPC" placeholder="i.e. 12">
            </div>
        </div>
        <div class="form-group">
            <label for="inputNotes" class="control-label">Notes</label><br>
            <div class="col-sm-12">
                <input type="text" class="form-control" id="inputNotes" value="Default">
            </div>
        </div>
        <div class="form-group">
            <div style="margin-lefT:4%;">
                <button type="submit" class="btn btn-default">Submit Changes</button>
            </div>
        </div>
    </form>
    </div>

1 个解决方案

#1


4  

A friend helped me out and I was able to come up with an answer! It was simple using jQuery as anticipated.

一位朋友帮助了我,我能够得到答案!按预期使用jQuery很简单。

Front-End:

前端:

The only thing that changed was the HTML select tag gained an onchange="fillForm()" attribute which would call a JS function anytime a serial number was selected.

唯一改变的是HTML select标签获得了onchange =“fillForm()”属性,该属性可以在选择序列号时随时调用JS函数。

<select class="form-control" onfocus="this.blur()" id="inputSC" onchange="fillForm()">

Back-End:

后端:

I created a JS file with several functions pertaining to this form but in particular the fillForm() function.

我创建了一个JS文件,其中包含与此表单有关的几个函数,但特别是fillForm()函数。

function fillForm() {
    var val = $('#inputSC').val() // selected value
    val = val.replace('/', '-');
    $.getJSON('/json/' + val, function (data) {
        //printJSON(data);
        $('#inputRack').val(data.rack);
        $('#inputNotes').val(data.notes);
        $('#inputComtrol').text(data.comtrol);
        $('#inputPort').val(data.ctrl1.port);
        $('#inputAPC').val(data.ctrl1.apc);
    });
}

And for those who are not very good with JavaScript/jQuery, this function first retrieves the value of the drop-down select tag (note that selecting a new value from the drop-down on the page triggers this function) and then formats the string (something specific to my application). Then using jQuery, it calls $.getJSON(url [, data] [,success]); (here's the documentation) to retrieve the serial-specific JSON from the URL I had already set up in my routes, and then changes the values of each of the fields in the form to the data from the JSON. In my opinion, it's easier to think of the $.getJSON signature as $.getJSON(url, callback);, but refer to the documentation for official knowledge.

对于那些不太熟悉JavaScript / jQuery的人来说,这个函数首先检索下拉选择标记的值(注意,从页面上的下拉列表中选择一个新值会触发此函数),然后格式化字符串(特定于我的申请)。然后使用jQuery,它调用$ .getJSON(url [,data] [,success]); (这是文档)从我在路由中设置的URL中检索特定于串行的JSON,然后将表单中每个字段的值更改为JSON中的数据。在我看来,将$ .getJSON签名视为$ .getJSON(url,callback);更容易,但请参阅文档以获取官方知识。

It worked!

有效!

Feel free to comment with questions that I will attempt to answer!

请尽快评论我将尝试回答的问题!

#1


4  

A friend helped me out and I was able to come up with an answer! It was simple using jQuery as anticipated.

一位朋友帮助了我,我能够得到答案!按预期使用jQuery很简单。

Front-End:

前端:

The only thing that changed was the HTML select tag gained an onchange="fillForm()" attribute which would call a JS function anytime a serial number was selected.

唯一改变的是HTML select标签获得了onchange =“fillForm()”属性,该属性可以在选择序列号时随时调用JS函数。

<select class="form-control" onfocus="this.blur()" id="inputSC" onchange="fillForm()">

Back-End:

后端:

I created a JS file with several functions pertaining to this form but in particular the fillForm() function.

我创建了一个JS文件,其中包含与此表单有关的几个函数,但特别是fillForm()函数。

function fillForm() {
    var val = $('#inputSC').val() // selected value
    val = val.replace('/', '-');
    $.getJSON('/json/' + val, function (data) {
        //printJSON(data);
        $('#inputRack').val(data.rack);
        $('#inputNotes').val(data.notes);
        $('#inputComtrol').text(data.comtrol);
        $('#inputPort').val(data.ctrl1.port);
        $('#inputAPC').val(data.ctrl1.apc);
    });
}

And for those who are not very good with JavaScript/jQuery, this function first retrieves the value of the drop-down select tag (note that selecting a new value from the drop-down on the page triggers this function) and then formats the string (something specific to my application). Then using jQuery, it calls $.getJSON(url [, data] [,success]); (here's the documentation) to retrieve the serial-specific JSON from the URL I had already set up in my routes, and then changes the values of each of the fields in the form to the data from the JSON. In my opinion, it's easier to think of the $.getJSON signature as $.getJSON(url, callback);, but refer to the documentation for official knowledge.

对于那些不太熟悉JavaScript / jQuery的人来说,这个函数首先检索下拉选择标记的值(注意,从页面上的下拉列表中选择一个新值会触发此函数),然后格式化字符串(特定于我的申请)。然后使用jQuery,它调用$ .getJSON(url [,data] [,success]); (这是文档)从我在路由中设置的URL中检索特定于串行的JSON,然后将表单中每个字段的值更改为JSON中的数据。在我看来,将$ .getJSON签名视为$ .getJSON(url,callback);更容易,但请参阅文档以获取官方知识。

It worked!

有效!

Feel free to comment with questions that I will attempt to answer!

请尽快评论我将尝试回答的问题!