如何生成 ajax 表单?
你保留<form>
吗? - javascript 文件中的代码并使用 ajax(例如 JSON)加载数据,或者加载生成的 html 文件(包含您刚刚推送到浏览器的所有 <form>
和 <input>
)?或者还有其他更简单的方法吗?
如果您使用任何框架,您是否可以从模型中自动生成表单?
您认为什么最容易保持和维护? 有没有您觉得有用的插件或库,也许是 jQuery 的一些东西?
最佳答案
jQuery库中有一个解决方案
jQuery.get( url, [data], [callback], [type] )
Load a remote page using an HTTP GET request. This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.
$.get() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.
示例:
$.get("someForm.pl", { name: "John" },
function(data){
$(data).appendTo(document.body); // you might place it somewhere else
});
编辑:
仅更改现有 dom 的值的示例:
<form id="myForm"><input id="myName" /></form>
$.get("someForm.pl", { name: "John" },
function(data){
$("#myForm").each(function(){
this.value = data[this.id];
});
},"json");
您的服务器响应将:
{ 'myName' : 'John' }
关于javascript - 如何使用 AJAX 生成表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1538579/