【问题标题】:how to use ajax in wordpress to show database columns using php and Json如何在 wordpress 中使用 ajax 使用 php 和 Json 显示数据库列
【发布时间】:2016-02-15 23:04:11
【问题描述】:

我是使用 ajax 的新手,我有一个代码可以从 wordpress 中显示来自数据库列的一些信息。 我有这个 PHP 代码来连接数据库并创建 JSON 文件:

<?php    
$username = $_REQUEST['username']; 
$password = $_REQUEST['password'];    

if (isset($username) && isset($password)) {
//CONEXION
    $host="localhost";
    $user="DB_Username";
    $pass="DB_Password";
    $dbname="DB_Name";

//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname) 
or die("unexpected error");

//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8"); 

if(!$result = mysqli_query($conexion, $sql)) die();

$clients = array();

$num_result = mysqli_num_rows($result);

    if ($num_result == 0) {
        $clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
    } else {
        while($row = mysqli_fetch_array($result)) 
        { 
            $id=$row['ID'];
            $Name=$row['Name'];

            if ($row['A_Login'] == $username && $row['A_Password'] == $password){        
                $clients[] = array('id'=> $id, 'Name'=> $Name);
                } else {
                    $clients[] = array('error'=> "true", "msg" => "Incorrect data");
                    }

        }
    }

$close = mysqli_close($conexion) 
or die("Unespected error with DB");
  }
else {
    $clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}   
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;

?>

在 wordpress 页面中我有这段代码,我构建了一个表单,如果用户单击提交按钮调用 doLogin()

<script type="text/javascript"> function doLogin(){
    data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
    console.log(data);
    jQuery.ajax({
    type: "POST",
    url: "Mywebsiteurl.php",
    data: data,
    beforeSend: function(){

    },
    success: function(data){
        console.log(data);
        //var arr = JSON.parse(data);
        //$('#forma').html(data);

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error");
        console.log(textStatus);
        console.log(errorThrown);
    }
});
} </script>

我需要在&lt;div id="forma"&gt;中显示一种list ussign html,例如:

ID:值 ID 名称:值名称

还有更多信息...

当我尝试使用 $('#forma').html(data); 在我的网站上打印所需信息时,我收到错误或只是一个空白区域。

我该如何解决?谢谢。

【问题讨论】:

  • 信息是来自其他数据库还是来自 WordPress 数据库??

标签: php jquery json ajax wordpress


【解决方案1】:

在 WordPress 中,我们需要在此处将 ajax 挂钩挂钩到您的 check_user 函数。

add_action('wp_ajax_your_action_from_js', 'your_function');

//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');

检查下面的代码,了解它是如何根据您的上下文完成的。

在functions.php中

function check_user() {
    $username = $_REQUEST['username']; 
    $password = $_REQUEST['password'];    

    if (isset($username) && isset($password)) {
    //CONEXION
        $host="localhost";
        $user="DB_Username";
        $pass="DB_Password";
        $dbname="DB_Name";

    //Conexion
    $conexion = mysqli_connect($host, $user, $pass,$dbname) 
    or die("unexpected error");

    //gWe made the search
    $sql = "SELECT * FROM Column WHERE A_Login='$username'";
    mysqli_set_charset($conexion, "utf8"); 

    if(!$result = mysqli_query($conexion, $sql)) die();

    $clients = array();

    $num_result = mysqli_num_rows($result);

        if ($num_result == 0) {
            $clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
        } else {
            while($row = mysqli_fetch_array($result)) 
            { 
                $id=$row['ID'];
                $Name=$row['Name'];

                if ($row['A_Login'] == $username && $row['A_Password'] == $password){        
                    $clients[] = array('id'=> $id, 'Name'=> $Name);
                    } else {
                        $clients[] = array('error'=> "true", "msg" => "Incorrect data");
                        }

            }
        }

    $close = mysqli_close($conexion) 
    or die("Unespected error with DB");
      }
    else {
        $clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
    }   
    //We build the JSON
    $json_string = json_encode($clients);
    echo $json_string;
}

add_action('wp_ajax_check_user', 'check_user');

//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');

在你的 JS 调用文件中。

在脚本中,action 与您的 _your_action_from_js 相关。因此需要采取行动来了解 ajax 必须命中的位置。在我们的例子中,它执行我们的 check_user 并返回适当的值。

<script type="text/javascript"> 
function doLogin(){
    data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
    console.log(data);
    jQuery.ajax({
        type: "POST",
        url: ajax_url,
        data: data,
        beforeSend: function(){

    },
    success: function(data){
        console.log(data);
        //var arr = JSON.parse(data);
        //$('#forma').html(data);

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error");
        console.log(textStatus);
        console.log(errorThrown);
    }
});
} 
</script>

参考简单 AJAX 表单:http://wptheming.com/2013/07/simple-ajax-example/

法典参考:https://codex.wordpress.org/AJAX_in_Plugins

【讨论】:

    【解决方案2】:

    WordPress 具有启用 ajax 请求的特定方法。

    // registering ajax request for Logged users
    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    
    // registering ajax request also for public area
    add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
    
    function my_action_callback() 
    {
        // Your code here
    
        wp_die(); // this is required to terminate immediately and return a proper response
    }
    

    叫它:

    jQuery(document).ready(function($) {
        var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
    
        jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            data: data,
            method: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(a,b,c) {
    
            }
        });
    });
    

    来源:https://codex.wordpress.org/AJAX_in_Plugins

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2020-01-25
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多