获取具有活动类的元素,然后使用jQuery在Ajax中发送它们 [英] Get elements with active class and send them in Ajax with jQuery
问题描述
如果我有此HTML:
<form>
<a href="#" data-name="color" data-value="yellow" class="active">
<a href="#" data-name="color" data-value="red">
<a href="#" data-name="color" data-value="orange">
<a href="#" data-name="fruit" data-value="banana" class="active">
<a href="#" data-name="fruit" data-value="apple">
<buton id="send">Send</button>
</form>
我如何通过Ajax创建具有所有< class ="active">
的数组,以便在PHP之后与它们一起使用?
How can I create an array with all the <a class="active">
through Ajax to play with them in PHP after ?
谢谢.
推荐答案
You need to use formData to send the value
and name
data attribute of element having active
class to your PHP
back end file.
有一个 NO
点创建一个 array
并再次遍历该 array
以发送/创建 formData
用于阿贾克斯那完全没有必要.
There is NO
point creating an array
and looping through that array
again to send / create formData
for ajax. That is totally unnecessary.
请注意:您可以不在 ajax
请求中发送 array
.因此,根据您的问题,您可能需要此解决方案.
Please note: You can NOT send an array
in an ajax
request. So your probably need this solution as per your question.
初始化 formData
,并将您的 name
和 value
属性附加到 $.each
中,然后发送使用 ajax
Initialize formData
and append your name
and value
attribute to it in a $.each
and then send that formData
using ajax
工作演示:
//Initilize formData
var formData = new FormData()
//Each through elements
$('a').each(function(index, element) {
//check all element with class active only
if ($(element).attr('class') == 'active') {
//append active class data-name and value
formData.append($(element).data('name'), $(element).data('value'))
}
})
//Click event
$('#send').click(function(e) {
e.preventDefault()
// Display the key/value pairs of formData - demo only
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
//call ajax on send button click
$.ajax({
url: 'some_url.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data)
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" method="post" enctype="multipart/form-data">
<a href="#" data-name="color" data-value="yellow" class="active">
</a>
<a href="#" data-name="color" data-value="red">
</a>
<a href="#" data-name="color" data-value="orange">
</a>
<a href="#" data-name="fruit" data-value="banana" class="active"></a>
<a href="#" data-name="fruit" data-value="apple">
</a>
<button id="send">Send</button>
</form>
这篇关于获取具有活动类的元素,然后使用jQuery在Ajax中发送它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!