使用JSON数组jquery根据下拉选择的选项填充输入字段



在用户从下拉列表中选择一个选项后,我正在尝试自动填充输入字段,使用从远程API调用接收的Jquery和JSON数据。

我的目标是让最终用户从下拉列表中选择一个客户(该列表是根据服务器发送的JSON数据动态填充的(,然后用存储在JSON数组中的客户详细信息填充输入字段。

当前,该列表加载并显示列表中的客户名称。然后,我可以将JUST客户名称填充到所有文本字段中。

编辑:我可以通过再次调用服务器或让服务器呈现页面来完成此操作。但我只希望我的应用程序对服务器进行2次调用,一次GET获取应用程序的JSON配置文件,然后一次PUT/POST更新记录我在服务器端使用Laravel 7.x。

我需要的是能够访问每个客户的其他密钥/值对。

这是我的JSON输出从API调用移除第一个"数据"顶级记住,这似乎允许我将它们排序到下拉列表中,否则它将全部作为一个空白下拉项。

[
{
"CUID": 5,
"can": "Acme",
"pmfn": "Krillin",
"pmln": "N/A",
"pmpe": "test1@test.com",
"pmpn": "7343253228",
"cct": "subContract",
"cgt": "unarmedGuard",
"created_at": "2020-03-29T19:12:47.000000Z",
"updated_at": "2020-03-29T19:12:47.000000Z"
},
{
"CUID": 15,
"can": "test",
"pmfn": "john",
"pmln": "wick",
"pmpe": "djdja@jdjdjdj.com",
"pmpn": "55555555556",
"cct": "directContract",
"cgt": "armedGuard",
"created_at": "2020-03-30T18:14:52.000000Z",
"updated_at": "2020-03-30T19:44:56.000000Z"
},
{
"CUID": 16,
"can": "test43",
"pmfn": "Jay",
"pmln": "silent bob",
"pmpe": "hdhdhd@gmail.com",
"pmpn": "7343253228",
"cct": "directContract",
"cgt": "unarmedGuard",
"created_at": "2020-03-30T19:46:07.000000Z",
"updated_at": "2020-04-02T01:29:10.000000Z"
},

这是我当前的Jquery函数

function populateCustomer (){
let url = 'http://10.1.10.96:8080/api/customerList'; //sets the url of the JSON data
let dropdown = $('#selectCustomerList'); // grabs the select element based on ID
dropdown.empty();
dropdown.append('<option selected="true" disabled>Customer</option>'); // adds a non-clickable default
dropdown.prop('selectedIndex', 0);
// Populate dropdown with list of customers
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.can).text(entry.can));
if(data.Status=="Success") // checks if drop down list item was grabbed
{
$("#can").attr('value', entry.can); //populates customer name inputer field from selected drop down item
$("#pmfn").attr('value', entry.pmfn);
//  $("#pmln").attr('value', entry.pmln);
}   
dropdown.change(function () {
$('#can').val(this.options[this.selectedIndex].value);
$('#pmfn').val(this.options[this.selectedIndex].value);
//$('#pmln').val(this.options[this.selectedIndex].text);
});
}) 
});
}
populateCustomer();

基本html

<label for="can"> Company Name</label>
<input type="text" name="customer_info" id="can" class="disabled" value="" readonly="readonly" />
<label for="pmfn">Property Mangers First Name</label>
<input type="text" name="customer_info" id="pmfn" value="" readonly="readonly" class="disabled" />

好的,终于想通了。

首先-在我的php路由中,我删除了我的代码,该代码剥离了JSON文件的原始"数据"顶级成员。

我最大的错误是假设$.getJSON自动为您解析正确的JS数组。因此,一旦我弄清楚了,它就在makeArray和JSON.parse之间来回切换

所以我继续使用strigify,然后使用JSON.parse。在这之后,我可以使用来自服务器的适当JSON将它们重新添加到我的下拉列表中。

这就是.change和selectIndex的作用。我读过你可以使用.bind,但.change似乎对我的情况很好。

然后,代码侦听更改下拉列表项的用途-然后它将i分配给所选的下拉列表项适当的索引号-我们需要从这个数字中减去-1,因为selectIndex将元素索引从1开始,而不是像JSON数据的JavaScript数组那样从0开始。

从这一点开始,我们就可以用识别的常规JavaScript对象/数组填充字段/元素。

这是Javascript函数

function populateCustomer (){
	let url = 'http://10.1.10.96:8080/api/customerList'; //sets the url of the JSON data
	let dropdown = $('#selectCustomerList'); // grabs the select element based on ID
	dropdown.empty();
	dropdown.append('<option selected="true" disabled>Customer</option>'); // adds a non-clickable default
	dropdown.prop('selectedIndex', 0);
	var custObj = $.getJSON(url, 
	function(data){ //grabs JSON data from URL and runs callback functions to change the data to JS format
		var x = JSON.stringify(data); //converts json data to string
		//console.log(x);
		x = JSON.parse(x); //parses proper json string to JS object
		
		//console.log(x); //logs all of the parsed data to console in proper JS format- SUCCESS
		//console.log(x.data[5].can); // checks to make sure that I can access the object properly -SUCCESS
		//populate dropdowns
		$.each(x.data, function (key, prop) {
		    dropdown.append($('<option></option>').attr('value', prop.can).text(prop.can));
		});
		// grabs the selected dropdown list items index ID
		$('#selectCustomerList').change(function() { //functions listens for change on the dropdown box
		var i = this.selectedIndex; // sets i to the selected index value
		//console.log(i); // checks that we can grab the selected index int -SUCCESS!
		/*
		sets i to match the appropriaite array index. 
		When using selectIndex the Index starts at 1 not 0 so we have to set it back -1
		*/
		i = i - 1; 
		// appends the property managers first name element with data stored within the array
		 $('#can').attr('value', x.data[i].can).text( x.data[i].can); // can - customer account name
		$('#pmfn').attr('value', x.data[i].pmfn).text( x.data[i].pmfn); //pmfn - property managers first name
		$('#pmln').attr('value', x.data[i].pmln).text( x.data[i].pmln);// pmln - property managers last name
	});
	});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> test </title>
</head>
<body>

<fieldset>
<select id="selectCustomerList" name="selectCustomerList">
<option value="">Customer / Property </option>
</select> <br />
</fieldset>

<fieldset>
<label for="can"> Company Name</label>
<input type="text" name="customer_info" id="can" class="disabled" value="" readonly="readonly" />
<label for="pmfn">Property Mangers First Name</label>
<input type="text" name="customer_info" id="pmfn" value="" readonly="readonly" class="disabled" />
<label for="pmln">Property Mangers Last Name</label>
<input type="text" name="customer_info" id="pmln" value="" readonly="readonly" class="disabled" />
</fieldset>
</body>
</html>

希望这能帮助其他人!

非常感谢您发布您的代码,这很清楚,它帮助了我同样的努力。

我也看了这个简短的教程,最后,我设法使它发挥作用。但奇怪的是,我根本不需要解析json代码。

这是我的工作代码:

// I define all my inputs as variables
let dropdown = $('#dci');
let input1 = $('#family');
let input2 = $('#interactions');
let input3 = $('#cat');
// Here we append the options frOm the json data first field
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choisir un médoc</option>');
const url = 'http://localhost/celderga/interaction.json';
// I call my json file
$.getJSON(url, function(data) {
// for each row I grab the key and value of my first field
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.DCI).text(entry.DCI));
}); 
// and then at each select' change I add the value of the others fiels in my inputs
$('#dci').change(function()  {
var i = this.selectedIndex; 
i = i - 1; 
input1.addClass(data[i].Famille);
input2.text(data[i].Interaction);
input3.text(data[i].CAT);
});
});

在我看来,它更简单、更短,不明白为什么你必须转换和解析json。。。也许我做错了,但这是有效的。。

json文件看起来像这个

[{

"DCI": "Antidépresseurs tricyliques",
"Famille": "antidepresseurs",
"Interaction": "Sub. du CYP2D6",
"CAT": "Diminuer la dose du traitement concomitant"
},{
...
}]

最新更新