【问题标题】:Jquery ajax and for each variable?Jquery ajax 和每个变量?
【发布时间】:2021-06-05 11:27:18
【问题描述】:

在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>

【问题讨论】:

  • Alessio Cantarella 感谢您的编辑,您知道如何完成这项工作吗?

标签: jquery ajax variables foreach send


【解决方案1】:

您可以使用 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>

【讨论】:

  • 所以不可能以某种方式将 jquery ajax 键值设置为变量。好的,你能用javascript写除jqery ajax之外的所有东西吗,因为我不熟悉jquery脚本(如我上面的例子)
  • 嗨,你可以在你的ajax中传递data,我已经在notes里面添加了这个var data = {.. 'note': notes //pass same };..,当你运行上面的代码时你可以看到data的输出sn-p。
  • Swati,received.php 页面可以读取 $_POST ['note1'], $_POST ['note2'] ...,这样
  • 所以你不需要它们在 json 数组中?你需要单独传递它们吗?使用上面的代码,您可以简单地使用 for 循环并获取所有 datas
  • 我需要单独切换它们以便接收它们。php可以分别读取...,如何?
猜你喜欢
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
相关资源
最近更新 更多