将 json 对象的值附加到输入字段

Appending values of json object to input field

本文关键字:输入 字段 json 对象      更新时间:2023-09-26

我正在尝试将json对象(name&color)的值附加到表单中的两个输入字段中。这是在我的网络服务器中进行的 api 调用的模型。jQuery 函数获取第一个输入字段的值,然后连接 url + json 文件位置,最后进行 api 调用。控制台显示已成功检索值,但我不确定如何相应地将它们附加到其输入字段中。网站

杰森:

{
    "name": "test1",
    "color": "red",
}

jQuery/AJAX

$(document).ready(function() {
  /** get the inputs we might need */
  var $result = $('#result');
  var $input = $('#input');
  $result.data('url', $result.val());
  var timer;
  /** function to submit data to the server and
      update the result input on success */
  function submitForm( input, newValue) {
    $.ajax({
      type: "GET",
      url: newValue,
      data: {input:input},
      dataType: 'json',
      success: function (data) {
        $result.val(newValue);
      }
    });
  };
  /** on key up, fill #result with the url + input */
  $input.bind('keyup', function() {
    var $this = $(this);
    var inp = $this.val();
    var url = $result.data('url');
    var newValue = url + inp + '/info.json';
    if(timer) { clearTimeout(timer); }
    timer = setTimeout(function(){
      submitForm(inp, newValue) ;
    }, 500);
    return false;
  });
});
我相信

问题是从对象(来自 JSON)中获取元素并将这些值提供给输入?

<input type="text" id="name">
<input type="text" id="color">

一个基本的例子:

var myobj = {"name":"botskonet","color":"blue"}
for( k in myobj ){
    document.getElementById(k).value = myobj[k];
}

小提琴