通过循环使用jQuery和Ajax
问题描述:
元素我有类鉴定项目清单和数据自定义属性如下:通过循环使用jQuery和Ajax
<div class="matrix_type" id="12" data-matrix-value="7"></div>
<div class="matrix_type" id="189" data-matrix-value="4"></div>
<div class="matrix_type" id="12090" data-matrix-value="10"></div>
<div class="matrix_type" id="1234" data-matrix-value="2"></div>
我想用一个按钮来触发一个AJAX发布<button id"send_matrix">Send<button>
一旦按钮被点击,我想要将每个“div”与它的值关联起来,我可以使用其他数据发送AJAX请求。
任何指南?
答
假设你想获得的所有div的,并通过“一”对象发布之前让所有的值迭代,请执行下列操作:
$('#send_matrix').click(function(){
// We post this to the server
var postObject = {};
//Get all the divs with the class of 'matrix_type' and iterate through
$('.matrix_type').each(function(){
//Get the id of the current div (please make them unique!)
var id = $(this).attr('id');
//Get the matrix value of the current div
var matrixValue = $(this).data('matrix-value');
//Add a new key-value pair to the postObject
postObject[id] = matrixValue;
});
//Replace this with the url you post the data to
var url = 'www.something.com'
//Post the data to the server
$.post(url, postObject, function(data, status){
//Show the result of the attempted post (success or failure)
alert("Data: " + data + "\nStatus: " + status);
});
});