如何在 jQuery 中获取具有特定父类的所有元素的内容,并将它们传递给 GET 变量

How can I get the contents of all elements with a specific parent class in jQuery and pass them in a GET variable?

本文关键字:GET 变量 jQuery 获取 父类 元素      更新时间:2023-09-26

我需要收集所有列表项的内容,父类为list_array,然后通过GET变量将它们传递给AJAX调用。 你能推荐一个策略吗?

这是一个小提琴。

.HTML:

<div>
    <ul class="list_array">
        <li>item A</li>
        <li>item B</li>
        <li>item C</li>
    </ul>
</div>
<p>some text</p>
<div>
    <ul class="list_array">
        <li>item B</li>
        <li>item C</li>
        <li>item D</li>
    </ul>
</div>
<p>some text</p>
<div>
    <ul class="list_array">
        <li>item A</li>
        <li>item C</li>
        <li>item E</li>
    </ul>
</div>

这是我目前的进展:

$(document).ready(function(){
    var listItemArr = [];
    $('.list_array li').each(function() {
        listItemArr.push($(this).text());
    });
    alert(listItemArr);
});

正如小提琴所示,这是行不通的。

理想情况下,我也只传递唯一的字符串,因此预期的结果将是:

item A
item B
item C
item D
item E

(并且不包含重复项)

此外,欢迎将数组传递到我的 PHP 处理页面的任何建议。

谢谢!

试试这个:

var arr = [];
$('.list_array li').each(function() {
    var t = $(this).text();
    if (arr.indexOf(t) === -1) {
        arr.push(t)
    }
})
// arr = arr.join(',')  
// =>  item A,item B,item C,item D,item E

演示

您可以使用 jQuery $.post $.ajax 实用程序函数将数据发送到 PHP:

  1. $.post()
  2. $.ajax()
  3. $.get()

不了解 PHP。这是客户端代码:

var arrayName = 'whatever';
//use an object as an SET to remove duplicated items
var dict = {};
$('.list_array li').map(function() {
    return $(this).text();
}).each(function(){
    dict[this] = '';
});
//retrieve the values saved to the SET
var params = '';
for(var k in dict)
    params += arrayName + '=' + k +'&';
//send request
$.get('/path/to/your.php', params, function (response) {
    console.log(response);
    //or do what ever you want with the response.
}, 'html');

试试这个

var all=[];
$('ul.list_array li').each(function(){
    var text=$(this).text();
    if($.inArray(text, all)==-1) all.push(text);
});
$.get('/url/to/page', {'items': all}, function(data){
    console.log(data);
});

变量 all 是一个类似于 ["item A", "item B", "item C", "item D", "item E"] 的数组,您的数组在$_GET中可用,如 $_GET['items'] .

检查此项以查看过滤后的数组。