我有一个显示赔率类型的选择字段。字段中的每个赔率调用不同的值,该值需要使用Ajax更改并显示在odds.php上。
如何使用jQuery和WP函数通过Ajax传递Select字段的值?
Odds.php
<select id="typeOdds" class="uk-select">
<option selected disabled>Choose Odds Type</option>
<option value="spread">Spread</option>
<option value="total">Total</option>
<option value="moneyline">Moneyline</option>
</select>
当赔率类型改变时,这是我需要从我的条件中改变的变量:
$pregameodds->AwayPointSpread
转换为$pregameodds->AwayMoneyLine
这是我的Ajax代码示例,但无处可去。。。
$('#typeOdds').change(function(){
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "post",
success: function(data){
// my value from select field
}
});
});
更新了我的问题:
我不知道什么时候我叫";typeOdds";。但在console.log和alert中,它显示了我的价值。
我的odds.js
jQuery('#typeOdds').on('change', function($) {
var val = jQuery('#typeOdds').val();
console.log( '_type is changed to ' + val );
var data = {
'action': 'my_action',
'type': 'post',
'typeOdds': val
};
jQuery.post(ajaxurl, data, function(response) {
alert( 'Got this from the server: ' + response );
});
});
我的功能.php
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
global $wpdb;
$typeOdds = $_POST['typeOdds'];
echo $typeOdds;
}
我对Odds.pp 的条件
if ( $typeOdds == 'spread' ) {
$spreadPoint = $pregameodds->AwayPointSpread;
} elseif ( my_action() == 'moneyline' ) {
$moneylinePoint = $pregameodds->AwayMoneyLine;
}
所以只需对您的代码进行一些轻微的修改:
$('#typeOdds').change(function(){
$.ajax({
data: {"typeOdds": $('#typeOdds').val()}, //this is where you pass the value
url: "/wp-admin/admin-ajax.php",
type: "post",
success: function(data) {
// this is where you do things with the data you receive in return from the php script
// so something like:
alert(data); // data being whatever the php echo's out
}
});
});
更新:更新答案以反映您的typeOdds变量。我发布的是myValue而不是typeOdds,所以要么我需要将我的更改为typeOdds;要么你需要将My Functions.php发布变量更改为myValue。