我对javascript非常陌生,所以我不知道怎么解决这个问题。我希望在ajax data:调用中添加一个for循环,而不是手动列出每个项。
jQuery(document).ready(function()
{
var $payment = {
card: 'ajax-card',
month: 'ajax-month',
year: 'ajax-year',
cvv: 'ajax-cvv',
zip: 'ajax-zip',
phone: 'ajax-phone'
};
jQuery.each( $payment, function($key, $val)
{
jQuery('.'+$val).attr({ id: $val });
});
jQuery('#pay-bill form input[type=submit]').click(function()
{
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data:
{
card: jQuery('#'+$card+' input').val(),
month: jQuery('#'+$month+' input').val(),
year: jQuery('#'+$year+' input').val(),
cvv: jQuery('#'+$cvv+' input').val(),
zip: jQuery('#'+$zip+' input').val(),
phone: jQuery('#'+$phone+' input').val()
},
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
});
Make a variable before calling $.ajax
, and make a loop to set the values.
var postData = {};
$.each($payment, function(k, v){
//postData[k] = $('#'+v+' input').val();
postData[k] = $('.'+v+' input').val();
});
$.ajax({
type: 'POST',
data: postData,
// ...
});
P.S. You don't need the loop you have (setting $('.'+$val).attr({ id: $val });
), you can just do $('.'+v+' input').val();
(inside a loop).
If the values you want to pass in are in a form you can use $('#myForm').serialize()
Replace the code after var $payment = {...}
by the code below. I have adjusted the loop where you're assigning IDs to the elements.
var data = {};
jQuery.each( $payment, function($key, $val)
{
var $element = jQuery('.'+$val);
$element.attr({ id: $val }); //<-- This line can be removed, depending on the
// circumstances
data[$key] = jQuery('input', $element).val();
});
jQuery('#pay-bill form input[type=submit]').click(function(){
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data: data,
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
If you want an each function that can iterate with key->value pairs, checkout underscore.js: http://documentcloud.github.com/underscore/#each
_.each({key:'value',key2:'value2'},function(value,key){
// access the key->value during each iteration
});