簡體   English   中英

代碼點火器 php 和 jquery - 如何從多個表中獲取數據並通過 ajax 返回

[英]code igniter php and jquery - how to get data from multiple tables and return it via ajax

I am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. 我遇到的問題是,連同返回到 jquery function 的數據,我還需要在另一個表中運行 PHP 循環中的一些數據。 Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. 這是兩個數據庫查詢:

function get_selected_member($member = null){
        if($member != NULL){
            $this->db->where('id', $member); //conditions
        }
        $query = $this->db->get('members'); //db name

        if($query->result()){
            $member_result = $query->row();
            return $member_result;
        }
    }

function get_all_groups(){
        $query = $this->db->get('groups');
        $result = $query->result();
        return $result;
    }

然后在 javascript function 中,我正在做的是說:

var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
    type: "POST",
    url: post_url,
    success: function(member)
    {
        //Add all the member data and...

        var post_url2 = "/index.php/control_form/get_all_groups/";
        $.ajax({
            type: "POST",
            url: post_url2,
            success: function(group)
            {
        //Create a dropdown of all the groups
            }
        });
    }
});

在 PHP 中,您可以將兩者合二為一,然后將其作為json變量回顯到 ajax。 因此,在 php 中,您需要進行如下更改

function get_member_with_group($member = null){
    $data['member'] = $this->get_selected_member($member);
    $data['group'] =  $this->get_all_groups();
    echo json_encode($data);
}

然后在 javascript 中,如下所示..

var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
    var member = response.member;
    //do with member
    var group = response.group;
    // do with group
});

希望對你有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM