Javascript从json输出获取内容并保存到变量

时间:2016-10-11 20:43:27

标签: javascript jquery html json

我有一个名为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;

这很有用,但需要变量&#34; obj&#34;从index_list.php获取值?ip =&#34; + host_ip

我从How to create HTML select option from JSON hash?

获取代码

感谢。

2 个答案:

答案 0 :(得分:1)

当用户点击时,您需要进行ajax调用:

 $.post( "index_list.php?ip="+theip, function(resp){
        obj = JSON.parse(resp);
        doExactlyWhatYouDidButWithThisObject(obj);          
    })
    .fail(function() {
        alert( "error" );
    });

我假设您正在使用jquery,但如果您不想使用jquery,则可以使用xmlhttprequest执行相同操作

答案 1 :(得分:1)

  

var url =“index_list.php?ip =”+ host_ip

     

$。get(url,function(data){obj = data;});