未定义的 ajax post with for 循环和字符串选择器

Undefined ajax post with for cycle and string selectors

本文关键字:循环 字符串 选择器 for with ajax post 未定义      更新时间:2023-09-26

这是我的jquery/ajax菜鸟:)

我想出了这个:

$(function() {  
  $("#moreAdd").click(function() {  
    var dataString = [];
    var selector = '#repeat0';
    var row;
    for(var i=0;$(selector).length != 0;i++){
        row = [];
        selector = '#repeat' + i;
        row.push($(selector).val());
        selector = '#distance' + i;
        row.push($(selector).val());
        selector = '#style' + i;
        row.push($(selector).val());
        selector = '#change' + i;
        row.push($(selector).val());
        selector = '#time' + i;
        row.push($(selector).val());
        dataString.push(row);
        selector = '#repeat' + (i+1); //to check it's finished the for
    }

    $.ajax({  
        type: "POST",  
        url: "/index.php/trainings/showAdd",
        data: dataString,
        dataType: 'json',
        success: function(data) {  
            $("div#addModalBody").html(data.html);
        }  
    });
    return false;
  });  
}); 

但我总是以一个空帖子结束。我认为选择器的东西无法正常工作,我可以创建一个字符串,然后使用该字符串按 id 选择吗?如果不是这样,如果有人能告诉我我错在哪里......

谢谢詹姆斯

我可以创建一个字符串,然后使用该字符串按 ID 选择吗?

是的,这样做没有错。选择器只是一个字符串,如果需要,您可以动态构建它。


但我总是以一个空帖子告终

我猜你的意思是发送到showAdd的数据是空的。这是因为您构建的数据是错误的。

从文档中

对象(传递给数据(必须是键/值对。

不这样做,你建立字符串数组(var dataString = [];(并将其转储到数据中(data: dataString(。数组不是键值对。这是一个键值对 {key:value, key:value} 所以你的数组就是你的值,你的键在哪里?

因此,如果您的方法需要参数(x)并且您想发送y.您应该这样做:

$.ajax({  
        type: "POST",  
        url: "/index.php/trainings/showAdd",
        data: {x:y},
        dataType: 'json',
        success: function(data) {  
            $("div#addModalBody").html(data.html);
        }  
    });

我不做PHP,所以我不确定服务器端应该是什么样子,并且您没有添加应发送到服务器代码的预期参数。

在这种情况下,您应该使用 class

<input type="text" id="repeat0" class="repeat" />
<input type="text" id="repeat1" class="repeat" />
<!-- apply class on elements for distance,style,change,time,etc.-->

你的代码会像,

var dataString = [];
$('.repeat').each(function(index,value){
    obj={};
    obj['repeat']=$(this).val();// repeat value
    obj['distance']= $('.distance:eq('+index+')').val();// let distance class for all distance values
    obj['style']= $('.style:eq('+index+')').val();// let distance class for all distance values
    obj['change']= $('.change:eq('+index+')').val();// let style class for all distance values
    obj['time']= $('.time:eq('+index+')').val();// let time class for all distance values
    dataString.push(obj);    // add data to final array
});
// your ajax code here