【问题标题】:How do I use Ajax in a Wordpress plugin?如何在 Wordpress 插件中使用 Ajax?
【发布时间】:2014-06-06 23:48:13
【问题描述】:

我有一个带有 2 个下拉框的 Wordpress 网站。当我在第一个下拉框中选择一个选项时,我希望用 PHP 函数中的数据刷新第二个选项。为此我需要ajax。但我正在努力将 ajax 绑定到 Wordpress。

HTML 如下所示:

<form method="get" action="http://siradjov.anex.at/playground/">
    <div class="form-inner">   
       <div class="listing-search-main">
            <input type="text" class="listing-search-text text" name="s" title="Coach House, Golf Course, Water View, etc" value="unique">
            <input type="submit" class="listing-search-submit btn btn-large btn-primary" name="search-submit" value="Search">
            </div><!-- .listing-search-main -->

       <div class="listing-search-details">
           <div class="listing-search-field listing-search-field-select listing-search-field-status">
           <select class="listing-search-status select" name="status">
              <option value="">Status</option>
              <option value="sale">Sales</option>
              <option value="rent">Rentals</option>
              <option value="foreclosure">Foreclosure</option>
           </select>

      <div class="listing-search-advanced " style="display: block;">
          <div class="listing-search-field listing-search-field-select listing-search-field-min">
           <select class="listing-search-min select" name="min">
              <option value="">Price (min)</option>
              <option value="100000">100.000</option>
              <option value="200000">200.000</option>
              <option value="300000">300.000</option>
              <option value="400000">400.000</option>
           </select>

现在,例如,当用户选择“销售”时,我希望第二个选择标签重新加载 PHP 数组中的匹配价格。

PHP 函数如下所示:

 <?php

$selectedStatus = $_POST['status'];


if($selectedStatus == "sale")
{

    // Set price (min) to select

    $fields['min']['type'] = 'select';

    // Set price (min) select options
    $fields['min']['data'] = array(
        '100000' => '120,000',
        '120000' => '200.000',
        '130000' => '300.000',
    );

    // Set price (max) to select

    $fields['max']['type'] = 'select';

    // Set price (max) select options

    $fields['max']['data'] = array(
        '100000' => '120,000',
        '120000' => '200.000',
        '130000' => '300.000',
    );


}
else if($selectedStatus == "rent")
    {

        // Set price (min) to select

        $fields['min']['type'] = 'select';

        // Set price (min) select options
        $fields['min']['data'] = array(
            '200' => '200',
        );

        // Set price (max) to select

        $fields['max']['type'] = 'select';

        // Set price (max) select options

        $fields['max']['data'] = array(
            '200' => '200',
        );

    }

echo $fields;

我已将我的 jQuery Ajax 调用保存在一个单独的 .js 文件中。代码如下:

 jQuery(document).ready(function() {
jQuery(".listing-search-status.select[name='status']").change(function() {

        if (this.value == "sale")
        {
            jQuery.ajax({
                type: "POST",
                url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
                    data: { status : "sale" },
                    success: function(data) 
                    {
                      alert('Sale' + data['min']['data'][0]);
                    }
                     });
        }
        else
        {
            if (this.value == "rent")
            {
                jQuery.ajax({
                    type: "POST",
                    url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
                    data: { status : "rent" },
                                            success: function(data) 
                        {
                       alert('Rent' + data['min']['data'][0]);
                        }
                                     });
            }
        }

  });
 });

但警报框不显示。我也没有在 Google Chrome 的控制台上收到任何错误消息。谁能帮帮我?

【问题讨论】:

    标签: javascript php jquery ajax wordpress


    【解决方案1】:

    使用 Wordpress 提供给您的本地方法来利用 ajax 请求。

    在您的插件文件中,我们需要添加几个操作,以便我们可以通过 admin-ajax.php 文件发送 ajax 请求并解析它们。

    add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
    add_action('wp_ajax_ajax_request', 'ajax_controller');
    

    现在我们在插件文件中构建了一个 ajax 控制器。这样做的目的是充当控制器,根据ajax 请求提供的FN 参数切换其输出(稍后会详细介绍)

    ​​>
    function ajax_controller(){
        $ret = ''; //our return variable
        switch($_REQUEST['fn']):
            case 'status' :
                $ret = update_status($_REQUEST['status']);
                break;
        endswitch;
        echo $ret;
        die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
    }
    

    请注意,update_status() 函数是为了封装您上面的 php 代码而创建的。

    现在我们已经绑定了动作,以及一个我们可以无休止地用来检索数据的控制器。我们只需要对 ajax 调用进行一些修改。首先,我们可以对“出租/出售”开关使用三元分配,而不是 2 次 ajax 调用,这将清理一切。其次,我们需要将url地址改为/wp-admin/admin-ajax.php文件。

    var $status = (this.value == "sale") ? this.value : 'rent';
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: { 
           action: 'ajax_request', 
           fn : 'status', //this is the $_REQUEST['fn'] from above
           status : $status },
        success: function(data){
            alert('Sale' + data['min']['data'][0]);
        }
    });
    

    action 参数是必需的,fn 是我的编码原则的结果。 action 属性必须直接匹配 add_action('wp_ajax_nopriv_add_action('wp_ajax_ 之后的内容。

    这应该可以解决它。

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 2018-01-20
      • 2014-11-09
      • 2011-12-04
      • 2014-11-12
      • 1970-01-01
      • 2011-10-03
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多