您好,我目前正在开发wordpress应用程序。我已经能够完成应用程序所需的几乎所有内容。我甚至能够使用Jquery Ajax将数据插入到我的自定义数据库表中,并获得提交的背景反馈。
但我现在的目标是根据下拉选择自动填充文本字段。我在网上读了几篇文章,我在这里看到了答案Why is my AJAX call not working? 但我仍然无法解决问题,以下是我的代码:
/* Fetching file from the database*/
wp_enqueue_script(\'jquery\');
function ajaxAutopopulate() {
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST[\'package\'] ) ) {
$birdday = $_REQUEST[\'package\']; // department day
global $wpdb;
// Let\'s take the data that was sent and do something with it
$results = $wpdb->get_results("SELECT body_weight, daily_intake, fcr FROM bird_weight WHERE day=$birdday");
$users_arr = array();
foreach ( $results as $result ) {
$bweight = $result->body_weight;
$dintake = $result->daily_intake;
$fcr = $result->fcr;
$users_arr[] = array("body_weight" => $bweight, "daily_intake" =>$dintake,"fcr"=>$fcr);
}
// encoding array to json format
echo json_encode( $users_arr);
} else {
echo "error";
}
// Always die in functions echoing ajax content
die();
}
add_action( \'wp_ajax_ajaxAutopopulate\', \'ajaxAutopopulate\' );
add_action( \'wp_ajax_nopriv_ajaxAutopopulate\', \'ajaxAutopopulate\' );
//The Html Form on the frontend
echo
\'<form action="" name="mybirdweight" method="post">
<div>
<select id="days" name="days">
<option value=" " > Select Your Bird Age</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
</select>
</div>
<div>
<p>Body Weight</p>
<input id="bweight" type="text" name="bweight" value=""/>
</div>
<div>
<p>Daily Intake</p>
<input id="dintake" type="text" name="dintake" value=""/>
</div>
<div>
<p>FCR</p>
<input id="fcr" type="text" name="fcr" value=""/>
</div>
</form>\';
//Here is the jquery-ajax javascript
/* the jquery ajax request*/
echo <<< END
<script type="text/javascript">
jQuery(document).ready(function(){
// On change of the dropdown do the ajax
jQuery("#days").change(function() {
var package = jQuery(this).val();
jQuery.ajax({
// Change the link to the file you are using
url: "/wp-admin/admin-ajax.php",
type: \'POST\',
// This just sends the value of the dropdown
data: {package: package},
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals =JSON.parse(response);
// These are the inputs that will populate
jQuery("input[name=\'bweight\']").val(Vals.body_weight);
jQuery("input[name=\'dintake\']").val(Vals.daily_intake);
jQuery("input[name=\'fcr\']").val(Vals.fcr);
}
});
});
});
</script>
END;
请问我在哪里错过了它?
SO网友:Sumit Parkash
您需要更改在ajax请求中发送的数据。要让ajax在WordPress中工作,您需要发送action ajax post请求中的变量。改变
data: {package: package},
至
data: {action: \'ajaxAutopopulate\', package: package}
您还可以使用wordpress默认功能
wp_send_json( $response )
用于数据编码和
admin_url( \'admin-ajax.php\' )
用于ajax文件url。
如果js代码位于单独的文件中,则可能需要使用
wp_localize_script
将值传递给js文件