获取具有活动类的元素,然后使用jQuery在Ajax中发送它们 [英] Get elements with active class and send them in Ajax with jQuery

查看:53
本文介绍了获取具有活动类的元素,然后使用jQuery在Ajax中发送它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有此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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆