我的网站上有此表格:
<form action>
<input type = "number" placeholder = "Combat ID" name = "combat id" min = "0" max = "9999999999" required/>
<button type = "button" id = "check_button">Check</button>
<div class = "form-group">
<label for = "Character" style = "color:white;">Character</label>
<select id = "Character" name = "Character">
List of chars
</select>
</div>
<h2 style = "color:white;padding-top:2%;">Other info</h2>
...............
<button type = "submit" class = "btn btn-default">Submit!</button>
</form>
我想要的是,当您输入战斗ID时,单击“检查”按钮,然后在选择框中仅显示该战斗中的这5个字符。当向API提交战斗ID时,我会从API中获得这5个字符的名称。
因此,当用户单击“检查”按钮时,我需要使用给定的战斗ID向API发送请求,然后相应地填充选择标签。
最佳答案
我不会用汤匙喂饱您并告诉您一切,但我会给您一个良好的开端。
既然您已经允许使用jQuery,那么我将执行以下操作:
jQuery代码:<input id="combat-id" type = "number" placeholder = "Combat ID" name = "combat id" min = "0" max = "9999999999" required/>
基本上,我为“战斗ID”字段指定了combat-id
现在,在此JS代码上,您要做的是,在jQuery库中调用$()函数,并将选择器#check_button
传递给它,然后向其添加事件侦听器。您在选择器上调用on函数,并以字符串的形式为第一个参数提供操作,在第二个参数中,传递一个闭包以在发生此事件时执行。
在第一行,您在#combat-id
字段中获取值。
$('#check_button').on('click', function (event) {
var combatId = $('#combat-id').val();
// Do what you want with it now.
event.preventDefault();
});
调用
event.preventDefault();
可以阻止页面刷新。第二个参数中的闭包传递了一个事件变量,该事件变量可用于在事件中执行各种操作。所以现在,您只需要立即调用API并填充列表即可。您可以轻松完成。
如果您想执行POST请求,请执行以下操作:
$.post('/url/to/go', { var: val, combatId: combatId });
或对于GET请求:
$.get('/url/to/go', { var: val, combatId: combatId });
由于您使用的是PHP,因此可以这样获得
combatId
:$_GET['combatId']
或$_POST['combatId']
取决于您选择的REQUEST方法。您可以将每个请求分配给一个变量,如下所示:
var request = $.post(....);
并执行类似的操作:
request.success( function (data) {
// the data variable will have data you displayed to the screen.
});
request.error( function (error) {
// this will be called if the request failed. The error variable will have some sort of error info.
});
因此,在此代码中,您可以在
.success()
函数中放入一些代码以填充列表。您可以做的是使用PHP以JSON格式输出内容,您可以像这样在JavaScript中对其进行解析:data = JSON.parse(data)
这样做是将JSON(JavaScript Object Notation,一种表示JS类对象的语言,即JavaScript中的String)转换为原生JavaScript对象的方法。
要附加,请给
<select>
标记一个ID,让我们说#select
然后,您可以选择它并向其添加字符串,如下所示:
$('#select').append('<option value="' + data.value + '">' + data.text + '</option>');
在这里,我假设数据是具有两个属性的对象:
value
和text
,并将该数据附加到<select>
列表中。关于javascript - 根据给定的按钮单击信息创建一个标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34535211/