如何在Wordpress插件中使用Ajax?

时间:2014-06-06 23:48:14

标签: javascript php jquery ajax wordpress

我有一个带有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>

现在,例如,当用户选择“Sales”时,我希望使用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控制台上收到任何错误消息。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

使用Wordpress为您提供的本机方法来利用Ajax请求。

在您的插件文件中,我们需要添加一些操作,以便我们可以发送ajax请求并通过admin-ajax.php文件对其进行解析。

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

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

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_之后的内容直接匹配。

这应解决它。