如何解决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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。