我有一个名为index_list.php 的 JSON 输出脚本,输出为:
{"index":"1","name":"VALUE1"},
{"index":"2","name":"VALUE2"},
{"index":"3","name":"VALUE3"},
选择:
<select name="selectId" id="selectId"></select>
JavaScript:
$(document).on("click", ".open-graphAdd", function () {
var host_ip = $(this).data('ip');
$(".modal-body #host_ip").val( host_ip );
html = "";
obj = {
"1" : "VALUE1",
"2" : "VALUE2",
"3" : "VALUE3"
}
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
document.getElementById("selectId").innerHTML = html;
这很好用,但需要变量“obj”从index_list.php?ip="+host_ip获取值
我从 How to create HTML select option from JSON hash? 获取代码
谢谢。
最佳答案
当用户点击时,需要进行ajax调用:
$.post( "index_list.php?ip="+theip, function(resp){
obj = JSON.parse(resp);
doExactlyWhatYouDidButWithThisObject(obj);
})
.fail(function() {
alert( "error" );
});
我假设您正在使用 jquery,但如果您不需要 jquery,您可以对 xmlhttprequest 执行相同的操作
关于Javascript 从 json 输出获取内容并保存到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39986402/