如何使用jQuery从PHP获取变量

How to use jQuery to get variable from PHP

本文关键字:获取 变量 PHP 何使用 jQuery      更新时间:2023-09-26

我正在尝试使用ajax和jQuery从MySQL获取数据。现在,唯一返回的是"0"。这是我的PHP函数:

function dallas_db_facebook_make_post () {
    global $wpdb;
    $query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
    $results = $wpdb->get_results($query, ARRAY_A);
    foreach($results as $result) {
        $fbpost =  $result['text'];
    }   
}

这是我的jQuery函数:

function send_fb_post() {
    jQuery.ajax({
        type: "GET",
        url: my_ajax.ajaxurl,
        data: {
            'action': 'dallas_db_facebook_make_post'
        },
        beforeSend: function() {
        },
        success: function(data){
            console.log(data);
        },
        error: function(){
        },
    });
};

你没有得到任何东西,因为你没有打印/回显任何东西。

如果您尝试会发生什么

foreach($results as $result) {
    echo $fbpost =  $result['text'];
}   

您的代码不起作用,因为您没有在服务器端打印任何内容。 因此,您可以像下面这样对代码进行小的更改。jsonencode 用于返回数据数组。

function dallas_db_facebook_make_post () {
    global $wpdb;
    $query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
    $results = $wpdb->get_results($query, ARRAY_A);
    $fbpost = array();
    foreach($results as $result) {
        $fbpost =  $result['text'];
    }   
    echo json_encode($fbpost);
    exit;
}

作为响应,您json_encodeed数据。您可以在响应回调中使用以下函数解码和使用这些数据。

function send_fb_post() {
    jQuery.ajax({
        type: "GET",
        url: my_ajax.ajaxurl,
        data: {
            'action': 'dallas_db_facebook_make_post'
        },
        beforeSend: function() {
        },
        success: function(data){
            console.log(jQuery.parseJSON( data ));
        },
        error: function(){
        },
    });
};