简体   繁体   English

使用JQuery动态地通过ajax以json格式发送表单数据

[英]Send post form data in json format via ajax with JQuery dynamically

I wander how send post form data in json format via ajax with JQuery dynamically? 我喜欢如何动态地通过ajax与jQuery以json格式发送表单数据? For example I'm coding something like this in JQ: 例如,我在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. 这很好,但在实时应用程序中经常需要发送大量的表单数据,用户可以动态更改字段,所以我不知道将发送多少func1,func2,func3甚至func []。 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. q是如何动态地执行此操作,在AJAX的旧世界中,我可以通过实现表单并发送到服务器来完成它。 Thanx in advance. Thanx提前。

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;
});

}); });

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. 可以为AJAX请求构建动态数据,但显然您需要知道检索该动态数据的逻辑。 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). 你没有在你的问题中描述这一点,所以在下面的例子中,我假设它基于表单中的.user_input字段的数量(可以是2,或10,或其他)。 The data is then comprised of field name + field value. 然后,数据由字段名称+字段值组成。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM