我是 html 和 java 脚本的新手。我尝试创建一个按钮并从 URL 返回 JSON,并将结果添加到下拉列表中。 Nodejs服务器启动运行后,如果输入http://localhost:8080/restapi/test/projects ,它将返回 {example} 作为结果。
所以这里有几个问题: 1) 由于某种原因,按钮点击在 jquery 中不起作用 2) $.getJSON 只能在jquery 中使用,有没有其他方法从URL 响应中获取JSON?
$(document).ready(function () {
$(document).on('click', '#button1', function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option = document.createElement('option');
option = d;
selector.add(option);
});
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='first'>
<h1>project options</h1>
<button id='button1'>Get Projects</button>
</div>
<div id='second'>
<h2>all projects</h2>
Projects: <select id='selector'></select>
</div>
感谢任何提示。
最佳答案
{example}
不是有效的 JSON。试试 {"1":"example"}
此外,option = d
;将覆盖您的选项。试试 option.value = d;
这是为您整理的版本:
$(document).ready(function () {
$('#button1').click(function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, {"1":"example","2":"other example"},function (data) {
$.each(data, function (index, d) {
selector.options[selector.options.length] = new Option(d,d);
});
});
});
});
关于javascript - 按钮单击在 jquery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36784768/