从返回JSON并填写html表单的URL读取?

时间:2018-03-09 14:47:31

标签: javascript jquery json

这个问题与这个问题非常相似(How to fill form with JSON?)。区别在于JSON来自URL,我不知道如何读取从该URL返回的JSON并存储在var中。

网址:http://MyServer/Results.json

此调用返回此JSON:

{ 
  "id" : 12,
  "name": "Jack",
  "description": "Description"
}

我只需要使用JSON流中的字段“description”填充<input> description 。该示例使用循环

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

我认为这个答案可以帮到你:https://stackoverflow.com/a/12460434

我将为您复制解决方案......

您可以使用jQuery .getJSON()函数:

$.getJSON('http://MyServer/Results.json', function(data) {
    //data is the JSON string
});

如果你不想使用jQuery,你应该看看纯JS解决方案的答案:https://stackoverflow.com/a/2499647/1361042

要填写输入字段,您可以使用:

 $("#description").val("10");

但因此您必须将id="description"设置为输入。

工作示例

https://jsfiddle.net/f7mpoyvw/3/

在这个例子中,我正在调用randomuser.me api,它将返回一个随机用户。从返回的用户,电子邮件地址将写入说明字段。

在你的例子中,你应该尝试:

$.getJSON('http://MyServer/Results.json', function(data) {
    $("#description").val(data['description']);
});

希望这会对你有帮助!

相关问题