简体   繁体   English

如何使用jQuery从PHP获取变量

[英]How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. 我试图使用ajax和jQuery从MySQL获取数据。 Right now, the only thing being returned is "0". 现在,唯一返回的是“ 0”。 Here is my PHP function: 这是我的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'];
    }   

}

Here is my jQuery function: 这是我的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(){
        },
    });
};

You are not getting anything, because you are not printing/echoing anything. 您没有得到任何东西,因为您没有打印/回显任何东西。

What happens if you try 如果尝试会怎样?

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

You code is not working because you are not print anything on server side. 您的代码无法正常工作,因为您没有在服务器端打印任何内容。 so you can small change in your code like below. 因此您可以像下面这样在代码中进行少量更改。 jsonencode is use to return an array of data. 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;
}

in response you json_encodeed data. 作为响应,您将json_encoded数据。 You can decode and use this data using below function in response callback. 您可以使用以下函数在响应回调中解码和使用此数据。

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(){
        },
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM