【问题标题】:wordpress search query with ajax带有ajax的wordpress搜索查询
【发布时间】:2015-02-21 17:05:51
【问题描述】:

我在 wordpress 中运行 wpdb 选择查询并从文本框中获取它的参数。只要我按下搜索按钮,结果就会显示出来。但我想在不刷新页面的情况下对 ajax 做同样的事情。我已经尝试了所有方法,但页面仍然刷新。

下面是我的代码

//jquery代码

jQuery(document).ready(function() {  

   jQuery("#Submityourskill").click(function(){


   jQuery.post(yes.ajaxurl,{action : 'doit'},

    function( response) {//start of funciton


      // alert(response);
       //jQuery("#searchtextbox").val(response);
       jQuery("#result").append(response);
       jQuery("#textarea").html(response);
       return false;
    });//end of function


   }); // click button function finishing here


}); //end of main loop 

html

<form action="" method="post">
<div><input maxlength="200" name="secretcode" size="200" type="text" value="" placeholder="Type Here !" />
<input id="Submityourskill" name="Submit" type="submit" value="Search Record" /></div>
</form>
<div id="result"></div>

//php函数

function doit() {
if(isset($_POST['secretcode'])!= ''){
if($_POST['Submit']) {

$secretcode=$_POST['secretcode'];
global $wpdb;

$sql = "SELECT * FROM wp_store_locator WHERE sl_description='$secretcode'";
$results = $wpdb->get_results($sql) or die(mysql_error());
 foreach( $results as $result ) {

  echo $result->sl_description;

    }
 exit();
}
  }

下面是我用过的其他php代码

php代码

add_action( 'wp_ajax_nopriv_doit', 'doit');
add_action( 'wp_ajax_doit', 'doit' );

下面是jquery页面入队的代码

function add_myjavascript(){  
wp_register_script( 'globals', get_stylesheet_directory_uri() . "/js/ajax-implementationn.js", array( 'jquery' ) ); 
wp_enqueue_script( 'globals' );

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'globals', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

}  

add_action( 'init', 'add_myjavascript' )

谢谢大家,问候...!

【问题讨论】:

    标签: jquery ajax wordpress


    【解决方案1】:

    收听表单的submit 事件,让您自己更轻松。除了单击提交按钮之外,还有其他提交表单的方法。

    您正在寻找的是防止event.preventDefault() 的默认操作:

    jQuery(document).ready(function() {  
    
        jQuery("#myform").submit(function(e){
            e.preventDefault();
            jQuery.post(yes.ajaxurl,{action : 'doit'}, function( response) {
                // alert(response);
                //jQuery("#searchtextbox").val(response);
                jQuery("#result").append(response);
                jQuery("#textarea").html(response);
                return false;
            });//end of function
        }); // submit form function finishing here
    }); //end of main loop
    

    并为您的表单提供id,以便您可以定位它:

    <form id="myform" action="" method="post">
    

    【讨论】:

    • 你好乔治,我已经按照你说的做了,但是现在我在搜索文本框中写下我的值后按下搜索按钮后返回 0
    • 请任何人帮助我...乔治解决方案看起来不错,但是在我在搜索文本框中写入并按搜索后我的结果为零
    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 2017-06-30
    • 2020-02-24
    • 2021-07-23
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多