jquery ajax问题

标签 jquery ajax loops css-selectors

几天前我发布了这个问题:switch statement and loops using jquery/javascript
最终我使用这段代码创建了一系列 div

  for (var i = 1; i <= $("#play option:selected").text(); ++i) {
    $("#play_"+i).slideDown().find("input").addClass("someClass");
  }  

我的问题是我现在需要获取每个 #play div 的值并通过 ajax 将其发送到 php 脚本。 如果我有一定数量的 div,我可以轻松做到这一点,但是当我不知道会有多少 #play 时我该怎么做?

进一步描述!

看来我在最初的问题中没有清楚地解释自己,所以我会尝试更好地解释事情。
我想使用 $.post jQuery 方法对远程 php 脚本进行 AJAX 调用。我可以非常轻松地发送远程脚本所需的信息。这是一个例子:

     $("#submit").click(function() {
              $.post("../includes/process.php",
                     {
                       play_0: $("#play\_0").val(),
                       play_1: $("#play\_1").val(),
                       play_2: $("#play\_2").val(),
                       play_3: $("#play\_3").val(),
                       play_4: $("#play\_4").val()                                
                     },
                     function(data) {
                       $("#activityWindow").empty().append(data);       
              });
    });

PHP 脚本现在可以通过 $_POST 数组访问此信息 - 就像普通的表单提交一样。
如果我使用循环生成了 div (#play_),则无法按照上面的方式对 $.post 方法进行硬编码。实际上,我需要在语法中的某个地方包含一个循环 - 我只是不知道如何做到这一点!我希望这能让事情变得更清楚。

最佳答案

jQuery 有一个 attribute startsWith选择器,然后您可以轻松地循环它们来创建您的对象...

// Create an empty object
var data = {};

// Get all <div> elements that have an id attribute that starts with "play_"
var divs = $("div[id^=play_]");

// Loop through the <div> elements, using jQuery's each function
divs.each(function() {
  // Get the current div we are looping with jQuery
  var div = $(this);

  // Get the ID of the current div
  var id = div.attr("id");

  // Get the value of the current div
  var val = div.html();


  // Object properties can be set dynamically like this in Javascript
  data[id] = val;
});

// Loop is done, all properties have been set
alert(data.play_0);

关于jquery ajax问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1179535/

相关文章:

jQuery: $(this).data() 为空

php - jQuery 使用 AJAX 显示从 PHP 文件获取的 PDF 数据

javascript - 当我回来时Ajax数据消失了

javascript - 数据表不应用每页过滤

AngularJS:使用 ng-repeat 在第一个元素上应用 CSS 类

javascript - 工具提示 Bootstrap 持续时间

jquery - Google Chrome 开发者工具 & 'known' 异常

java - 使用 Spring MVC 和 ajax 返回字符串时编码错误

bash - 在脚本 B 中运行脚本 A,然后退出脚本 B 而不退出脚本 A

loops - 在 Ansible 中,将 `with_items` 的使用替换为 `loop` 并使用内联定义的字典列表