dsfdsf48652 2013-09-24 17:46
浏览 67
已采纳

使用jQuery动态获取输入字段的值,并使用PHP处理它们

I am working on a page where I show different input fields, depending on the selection that a user did.

Example 1:

<input type="text" name="color" value="" id="5">
<input type="text" name="location" value="" id="6">
<input type="text" name="age" value="" id="7">

Example 2:

<input type="text" name="color" value="" id="5">
<input type="text" name="destination" value="" id="8">
<input type="text" name="hours" value="" id="9">
<input type="text" name="date" value="" id="10">

Question 1: How can I get all input fields with jQuery when the input fields itself are dynamic?

Question 2: On the serverside, I want to process the input fields with their value and ID. How can I make this dynamic?

I know that this can be done easily when everything is fix, e.g.:

var color =  $('#color').val();
var destination = $("#destination").val();

var dataString = 'color=' + color + "&destination=" + destination;
$.ajax({  
       type: "GET",  
       url: "do_something.php",  
       data: dataString,  
       async: false,
       success: function(data){
          console.log('success');
       }
});
  • 写回答

2条回答 默认 最新

  • doucu5836 2013-09-24 17:49
    关注

    You can use .serialize() to create your data-string. It will dynamically grab all the data for the form and turn it into a string like you're attempting to build:

    $.ajax({  
           type: "GET",  
           url: "do_something.php",  
           data: $("form").serialize(),  
           async: false,
           success: function(data){
              console.log('success');
           }
    });
    

    Docs for .serialize(): http://api.jquery.com/serialize

    Note, you may need to refine the $("form") selection to be more specific if you have more than one form in the DOM.

    As for your second question, you should generally keep questions on SO to one question per post. That being said, you should set the ID attribute to the value attribute instead, that way it will be passed to the PHP script when the form is submitted, ID will be lost since it's not transmitted with the form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛