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

Javascript从json输出中获取内容并保存到变量,javascript,jquery,html,json,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", fu

我有一个名为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获取值

我从你那里得到密码


谢谢。

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

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

我假设您使用的是jquery,但是如果您不想使用jquery,您也可以使用xmlhttprequest,当用户单击时,您需要进行ajax调用:

 $.post( "index_list.php?ip="+theip, function(resp){
        obj = JSON.parse(resp);
        doExactlyWhatYouDidButWithThisObject(obj);          
    })
    .fail(function() {
        alert( "error" );
    });
我假设您使用的是jquery,但如果不需要jquery,也可以使用xmlhttprequest

var url=index\u list.php?ip=+host\u ip

$.get url,函数数据{obj=data;}

var url=index\u list.php?ip=+host\u ip

$.get url,函数数据{obj=data;}


阅读ajax。哦,顺便说一句,你展示的不是一个有效的json。这里可能有数千个关于ajax的线程。可能的重复还请注意,你在PHP中生成的不是有效的json:你只允许一个顶级对象或数组。将其粘贴到ajax上的ReadUp中。哦,顺便说一句,你展示的不是一个有效的json。这里可能有数千个关于ajax的线程。可能的重复还请注意,你在PHP中生成的不是有效的json:你只允许一个顶级对象或数组。粘贴到