如何在 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?
我需要收集所有列表项的内容,父类为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:
- $.post()
- $.ajax()
- $.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']
.
检查此项以查看过滤后的数组。
相关文章:
- 如何使Jquery编码的动态下拉菜单与PHP GET变量协调工作
- 如何使用jQueryPOST将get变量从JavaScript传递到PHP-Mysql
- 检查是否已设置GET变量
- 如何获取get变量's值
- 如何在 jQuery 中获取具有特定父类的所有元素的内容,并将它们传递给 GET 变量
- 获取重复Get变量的查询字符串值
- 我们可以在javascript url中传递GET变量吗
- 使用javascript设置GET变量
- Javascript等同于PHP的GET变量
- jquery 从 javascript 文件中获取 GET 变量
- 使用 get 变量缓存静态 HTML 页面
- 在表单提交中添加额外的 GET 变量
- 在表单提交后将 get 变量附加到 url,而无需新的隐藏输入
- Javascript 删除所有具有历史推送状态的 get 变量
- 通过jQuery更改表单上的操作后,GET变量将消失
- 使用jQuery/Javascript访问GET变量
- 如何在jquery中从ajax响应中检索GET变量
- 将输入字符串转换为GET变量
- 将GET变量挂接到加载的JavaScript事件中
- 将GET变量从URL传递到.js,并从.js传递到.php