Javascript 使用JQuery通过ajax动态发送json格式的post表单数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11482939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send post form data in json format via ajax with JQuery dynamically
提问by Arthur Kushman
I wander how send post form data in json format via ajax with JQuery dynamically? For example I'm coding something like this in JQ:
我想知道如何通过 ajax 和 JQuery 动态发送 json 格式的表单数据?例如,我在 JQ 中编写了这样的代码:
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
and that's good, but in live apps often need to send huge form data and user can dynamically change the fields, so I don't know how many func1, func2, func3 or even func[] will be sent. The q is how to do this dynamically, in old world of an AJAX I could done it by serealizing the form and send to the server. Thanx in advance.
这很好,但是在实时应用程序中经常需要发送大量的表单数据,用户可以动态更改字段,所以我不知道会发送多少 func1、func2、func3 甚至 func[]。q 是如何动态执行此操作,在旧的 AJAX 世界中,我可以通过对表单进行序列化并发送到服务器来完成。提前谢谢。
回答by Arthur Kushman
Yes I can send all the data to the server and in any case it will worked well, example:
是的,我可以将所有数据发送到服务器,无论如何它都会运行良好,例如:
$(function() { // on document load
$('#email_form').submit(function() { // set onsubmit event to the form
var data = $('#email_form').serialize(); // serialize all the data in the form
$.ajax({
url: 'testJson.php', // php script to retern json encoded string
data: data, // serialized data to send on server
dataType:'json', // set recieving type - JSON in case of a question
type:'POST', // set sending HTTP Request type
async:false,
success: function(data) { // callback method for further manipulations
for (key in data.email) {
alert(data.email[key]);
}
},
error: function(data) { // if error occured
}
});
return false;
});
});
});
回答by Utkanos
It is possible to build up dynamic data for an AJAX request but clearly you'll need to know the logic for retrieving that dynamic data. You don't describe this in your question, so in the below example I'm assuming it's based on the number of .user_input
fields in the form (which could be 2, or 10, or whatever). The data is then comprised of field name + field value.
可以为 AJAX 请求构建动态数据,但显然您需要了解检索该动态数据的逻辑。您没有在问题中对此进行描述,因此在下面的示例中,我假设它基于.user_input
表单中的字段数(可能是 2、10 或其他)。然后数据由字段名称 + 字段值组成。
The point is to show dynamic collection of data, that's all.
重点是显示数据的动态收集,仅此而已。
var ajax_data = {};
$('.user_input').each(function() {
ajax_data[$(this).attr('name')] = $(this).val();
});
$.post('some/url.php', ajax_ata); //etc