Jquery ajax 和每个变量?

问题描述

在 javascript 中,这很容易,wordpress 需要 jquery ajax,而我对 jquery 不是最熟悉的。下面的例子可以用 ajax jquery 吗?

如何发送多个变量,使“var note++”加一,发送为:

note1 = "我的笔记 1",
note2 = "我的笔记 2",
note3 = "我的笔记 3",
note4 = "我的笔记 4",

还有更多.....

var i = "";
var note = "";
var divsname = document.getElementsByClassName("notes");
for (i = 1,i++) {
  divsname.forEach(function(div) {
    note += note i++ = div.innerHTML;
  });
  jQuery(document).ready(function($) {
    var data = {
      'action': 'my_actione','user_id': '1',note
    };
    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl,data,function(response) {
      alert('Got this from the server: ' + response);
    });
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">My note 1</div>
<div class="notes">My note 2</div>
<div class="notes">My note 3</div>
<div class="notes">My note 4</div>

解决方法

您可以使用带有索引号的 JSON 数组 发送您的 div 数据,值是您的 div 中的文本,然后将其传递给您的 ajax。

演示代码

var divsname = $(".notes");
notes = []
divsname.each(function(i) {
  //push in json array
  notes.push({
    [`note${i + 1}`]: $(this).text()
  })
});
var data = {
  'action': 'my_actione','user_id': '1','note': notes //pass same
};

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">My note 1</div>
<div class="notes">My note 2</div>
<div class="notes">My note 3</div>
<div class="notes">My note 4</div>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...