【问题标题】:How to pass the value from onchange select via Ajax to wp function and display on page如何通过 Ajax 将 onchange 选择中的值传递给 wp 函数并在页面上显示
【发布时间】:2020-08-06 18:51:03
【问题描述】:

我有一个显示赔率类型的选择字段。每个字段的赔率调用不同的值,该值需要使用 Ajax 更改并显示在 Odds.php 上。

如何使用 jQuery 和 WP 函数通过 Ajax 传递 Select 字段的值?

赔率.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-&gt;AwayPointSpread 转为$pregameodds-&gt;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 中显示的是我的值。

我的赔率.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.php 的条件

if ( $typeOdds == 'spread' ) {
  $spreadPoint = $pregameodds->AwayPointSpread;
} elseif ( my_action() == 'moneyline' ) {
  $moneylinePoint = $pregameodds->AwayMoneyLine;
}

【问题讨论】:

    标签: php jquery ajax wordpress


    【解决方案1】:

    所以只需对您的代码稍作修改:

    $('#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。

    【讨论】:

    • 我已经更新了我的问题.. 我仍然没有看到传递给我的 functions.php 的值
    • 到目前为止,我遇到了来自 admin-ajax.php 的 400 个错误请求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2021-12-01
    • 2013-03-08
    • 1970-01-01
    • 2011-03-29
    • 2012-07-29
    相关资源
    最近更新 更多