Js自动填充表单值

Autofill form values by Js

实际上我是一名 PHP 开发人员。我的一个项目中需要一点 Js。我曾尝试在 google 中搜索,但很快我发现我实际上并不知道我应该使用什么术语。现在学习整个 Js 是不可能的。 我需要的是,当用户点击一个按钮时,Js 将发送一个 API 请求,如 http://example.com/?id=56,获取 JSON 编码的数据并自动将它们插入带有输入字段的表单中,单选和复选框。 我认为代码会很简单,如果有人可以提供帮助,请帮忙。或者,如果有人至少可以指出我正确的方向,比如一篇文章或图书馆,那将非常有帮助。提前致谢。

首先,我认为对javascript有一个正确的理解会更好,而不是在没有真正理解发生了什么的情况下使用代码。

使用 jQuery 的一种方法是 $.getJSON() 方法。您可以下载 jquery 库 here

所以执行您所说的操作的代码应该是这样的:

$.getJSON( "http://example.com?id=56", function( data ) {
  // data contains the response from the server
  // Assuming data contains:
  // {
  //  "status": "success",
  //  "form_data": {
  //    "fname": "Kendrick",
  //    "lname": "Hanson",
  //    "age": "34",
  //    ...
  //  }
  // }

  // This assumes your form to be filled has a class of "js-filled" on it

  $('form.js-filled').find('.first-name').val(data.form_data.fname); // Fill the input field with class "first-name" with the fname in the response
  $('form.js-filled').find('.last-name').val(data.form_data.lname); // Fill the input field with class "last-name" with the lname in the response
});

本次访问 here,您可能希望使用 AJAX。在这里,您可能希望从请求的页面发送整个表单。但是,如果您想在同一页面中获取表单中的数据,则需要使用 AJAX 和 jQuery 来代替。 你会得到一些介绍 here.