如何在MySQL查询中使用WordPress中的AJAX?

时间:2016-11-28 作者:User014019

我有一个带有2个下拉列表和1个输入提交表单的自定义页面模板。当用户提交表单时,将显示结果,这工作正常。但我有一个问题,在获取数据库中的数据时,浏览器正在重新加载。

我想使用AJAX来防止重新加载页面。我看过一些关于Ajax WordPress的文章,但我不能正确地使用它。

有人能帮我吗?如何使用AJAX?如何在AJAX中调用自定义PHP文件?

AJAX(functions.php)

function ajax_enqueue_sl(){
    wp_enqueue_script(\'ajax_load_sl\', get_template_directory_uri().\'/js/alternate-dropdown.js\', array(\'jquery\'));
    wp_localize_script(\'ajax_load_sl\', \'ajax_object\', array(\'ajax_url\' => admin_url( \'admin-ajax.php\')));
}
add_action(\'wp_enqueue_scripts\', ajax_enqueue_sl);
带HTML的PHP(test.PHP)

$results_malls = $wpdb->get_results(\'SELECT DISTINCT street FROM tablename WHERE code IN ("test1") ORDER BY malls ASC\', OBJECT);
$results_stores = $wpdb->get_results(\'SELECT DISTINCT stores FROM tablename WHERE code IN ("test2") ORDER BY stores ASC\', OBJECT);

<form action=\'\' method=\'post\' name=\'myform\' id="myform">
<div class="pos-div">
<select name="street_list" id="filterbystreet">
    <option name="default" class="filter_by" value="Select by">Select by</option>
    <?php
    foreach($results_malls as $option){
        if(isset($_POST[\'street_list\']) && $_POST[\'street_list\'] == $option->malls)
            echo \'<option name="street_list" class="filter_by" selected value="\'. $option->street .\'">\'. $option->street .\'</option>\';
        else    
         echo \'<option name="street_list" class="filter_by" value="\'. $option->street .\'">\'. $option->street .\'</option>\';
     };
    ?>
</select>
</div>
<span class="or">or</span>
<div class="pos-div">
<select name="store_list" id="filterby">
    <option name="default" class="filter_by" value="Select by">Select by</option>
    <?php 
    foreach($results_stores as $option){
        if(isset($_POST[\'store_list\']) && $_POST[\'store_list\'] == $option->stores)
            echo \'<option name="store_list" class="filter_by" selected value="\'. $option->stores .\'">\'. $option->stores .\'</option>\';
        else    
         echo \'<option name="store_list" class="filter_by" value="\'. $option->stores .\'">\'. $option->stores .\'</option>\';
     };
    ?>
</select>
</div>
<input type="submit" value="List all partner stores" class="pos-submit"/>
</form>

if (isset($_POST[\'store_list\']) && $_POST[\'store_list\'] != \'Select by Store\'){
        $store_list = $_POST[\'store_list\'];
        $stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= \'" . $store_list . "\' AND code IN (\'test3\') ORDER BY street ASC", OBJECT));
        foreach ($stores as $record_s){
            echo \'<div class="records">\';
            echo \'<div><span>\' . $record_s->malls . \'</span></div>\';
            echo \'</div>\';
        }
    } elseif (isset($_POST[\'street_list\']) && $_POST[\'street_list\'] != \'Select by\'){
    $street_list = $_POST[\'street_list\'];
    $streets = $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE street_list= \'" . $street_list. "\' AND code IN (\'test3\') ORDER BY stores ASC", OBJECT));
    foreach ($streets as $record_m){
        echo \'<div class="records">\';
        echo \'<div><span>\' . $record_m->stores . \'</span></div>\';
        echo \'</div>\';
    }
}
ajax\\u js。js公司

jQuery(\'#filterbymall\').change(function(){
    jQuery(\'#filterbystore\').prop(\'selectedIndex\',\'Select by Store\');
});

jQuery(\'#filterbystore\').change(function(){
    jQuery(\'#filterbystreet\').prop(\'selectedIndex\',\'Select by\');
});

jQuery(\'#myform\').submit(ajaxSubmit);

function ajaxSubmit(){
    var myform= jQuery(this).serialize();

    jQuery.ajax({
        type:"POST",
        url: "/wp-admin/admin-ajax.php",
        data: myform,
        success:function(data){
            jQuery(".records").html(data);
        }
    });
return false;
}

1 个回复
SO网友:GKS

在WordPress中,处理ajax表单数据的默认方式有点复杂。像这样修改js代码。

function ajaxSubmit(e){

    // prevent the default action.
    e.preventDefault();

    var myform= jQuery(this).serialize();

    jQuery.ajax({
        type:"POST",
        // Get the admin ajax url which we have passed through wp_localize_script().
        url: ajax_object.ajax_url,
        action: "submitAjaxForm",
        data: myform,
        success:function(data){
            jQuery(".records").html(data);
        }
    });
return false;
}
在上面的JS代码中,我替换了表单url并添加了action参数。Wordpress为我们提供了一个统一的文件,即AdminAjax。php。它用于通过admin ajax调用服务器端PHP函数。php。如果未指定操作,请管理ajax。php将退出,并在过程中返回0。

Why form url replaced with ajax_object.ajax_url ?

因为您已经通过了管理ajax。使用wp\\u localize\\u脚本将php转换为JS文件。它还用于通过admin ajax调用服务器端PHP函数。php。如果未指定操作,请管理ajax。php将退出,并在过程中返回0。

Define form action.

要定义表单操作,我们需要使用wp_ajax_wp_ajax_nopriv_ 作为前缀。使用回调函数来处理这些表单数据
示例。

add_action(\'wp_ajax_{YourFormAction}\',\'{CallbackFunction}\');`
add_action(\'wp_ajax_nopriv_{YourFormAction}\',\'{CallbackFunction}\');
  • wp_ajax_nopriv_{YourFormAction} 为未登录的用户执行
将此代码添加到functions.php 文件

add_action(\'init\', \'registerFormAction\');

    function registerFormAction(){

        // To handle the form data we will have to register ajax action. 
        add_action(\'wp_ajax_nopriv_submitAjaxForm\',\'submitAjaxForm_callback\');
        add_action(\'wp_ajax_submitAjaxForm\',\'submitAjaxForm_callback\');

    }
Handle ajax form data

将要处理表单数据的所有代码放在回调函数中,我们最近使用了wp_ajax_{yourAction} 在上面

function submitAjaxForm_callback(){
    global $wpdb;
    if (isset($_POST[\'store_list\']) && $_POST[\'store_list\'] != \'Select by Store\'){
            $store_list = $_POST[\'store_list\'];
            $stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= \'" . $store_list . "\' AND code IN (\'test3\') ORDER BY street ASC", OBJECT));
            foreach ($stores as $record_s){
                echo \'<div class="records">\';
                echo \'<div><span>\' . $record_s->malls . \'</span></div>\';
                echo \'</div>\';
            }
        } elseif (isset($_POST[\'street_list\']) && $_POST[\'street_list\'] != \'Select by\'){
        $street_list = $_POST[\'street_list\'];
        $streets = $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE street_list= \'" . $street_list. "\' AND code IN (\'test3\') ORDER BY stores ASC", OBJECT));
        foreach ($streets as $record_m){
            echo \'<div class="records">\';
            echo \'<div><span>\' . $record_m->stores . \'</span></div>\';
            echo \'</div>\';
        }
    }

    // We must have to terminate, to get proper response.
    wp_die();
}
希望对您有所帮助!:)