我正在wordpress中工作,每次按下提交按钮时,我都想从表单中获取aid字段的更新值。有两个提交按钮,我希望id与单击的行一致
HTML表单(用php代码动态显示)
foreach( $results as $result ) {
$form.= \'<form id="voteform" action="" method="post">\';
$form.= "<input id=\'aid\' name=\'aid\' type=\'text\' value=\'$result->aid\'>";
$form.=" <input class=\'star\' class=\'star\' id=\'star5\' type=\'submit\' name=\'star5\' value=\'5\'>";
$form.=" <input class=\'star\' class=\'star\' id=\'star6\' type=\'submit\' name=\'star5\' value=\'5\'></form";
jQuery
$(document).on("click",".star", function(e) {
e.preventDefault();
var aidd = jQuery("#aid").val();
sentdata =({
action: \'star\',
aid:aidd,
})
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
alert(aid);
$("#myresult").html(res);
return false;
} //end of function
,
\'json\'); }); //end inner function
}); //end main function
php代码
add_action( \'wp_ajax_star\', \'star\' );
add_action( \'wp_ajax_nopriv_star\', \'star\');
function star()
{
$aid = $_POST[\'aid\'];
echo json_encode($aid);
die();
}
SO网友:TheDeadMedic
我有点困惑-为什么有两个提交按钮?你输出的是相同的id
多次(在foreach
循环),这将阻塞jQuery。使用类尝试以下操作:
$form = \'\';
foreach ( $results as $result ) {
$value = esc_attr( $result->aid );
$form .= \'<form method="post" class="aid-form">\';
$form .= "<input name=\'aid\' type=\'text\' value=\'$value\' />";
$form .= "<input name=\'star5\' class=\'star\' type=\'submit\' value=\'5\' />";
$form .= \'</form>\';
}
然后是jQuery:
$( document ).on( "submit", ".aid-form",
function( e ) {
e.preventDefault();
var data = {
action: "star",
aid: $( this ).find( "input[name=aid]" ).val() // Get value of "aid" from current form submitting
};
$.post(
yes.ajaxurl,
data,
function( result ) {
window.alert( result );
$( "#myresult" ).html( result );
},
"json"
);
}
);