2013-11-04 114 views
0

我正在絞盡腦汁,我需要通過jquery發送一個搜索值,以便在數據庫中進行全文搜索,然後將其顯示在div元素中。我需要在類別表和子類別表中搜索值。我想不出來,我認爲最好的辦法是,如果我發佈兩次(首先搜索類別,其次搜索子策略)。函數search_fulltext返回二維數組。從jquery post返回二維數組

我在想這樣的事情(我知道這並不工作,但只是想證明我多麼希望它的工作,我不知道如何使用二維數組處理)

// SCRIPT

function onclick_search_button(searching_value, at) 
{ 
// first post to search in categories 
$.post("search.php", {what:searching_value, where: at}, function(data,status){ 
// echo list of found results in CATEGORIES 
var found_items = eval(data); 
for(var i=0; i<found_items.length; i++) 
    { 
    $result = "Found in category: " + found_items[i]["cat_name"] + "and ID is: " + items[i]["cat_id"] + "</br>"; 
    $("#final_div_results").append($result); 
    } 

// second post to search in subcategories 
$.post("search.php", {what:searching_value}, function(data,status){ 
// echo list of found results in CATEGORIES 
var found_items = eval(data); 
for(var i=0; i<found_items.length; i++) 
    { 
    $result = "Found in category: " + found_items[i]["sub_cat_name"] + "and ID is: " + items[i]["cat_id"] + "</br>"; 
    $("#final_div_results").append($result); 
    } 
} 

// search.php中FILE

<? 
$inst = new DbQuery(); 

$what = $_POST["what"]; 
$where = $_POST["at"]; 

$result = $inst->search_fulltext($what, $where); 
// BUT SEARCH_FULLTEXT RETURNS TWO-DIMENSIONAL ARRAY SO I GUESS I CANNOT USE THE FOLLOWING 
echo json_encode($result); 
?> 

// HTML DIV

<div id="final_div_results">These are the results</div> 
+0

'json_encode'對於2d數組非常有效。附: *不要*做'eval(數據)'!在你的'$ .post'中添加''json''作爲第四個參數:'$ .post(「search.php」,{your:data},function(found_items){},'json');'。 –

回答

0

您可以返回一個json編碼的二維數組。然後你可以像這樣訪問返回的數據

$.ajax({ 
    type: "POST", 
    url: 'search.php', 
    data: {what:searching_value}, 
    success: function(data){ 
    for(var i=0; i<data.length; i++) 
    { 
     $result = "Found in category: " + data[i].sub_cat_name + "and ID is: " + data[i].cat_id + "</br>"; 
     $("#final_div_results").append($result); 
    } 
    }, 
    dataType: 'json' 
}); 
+0

非常感謝你們,那正是我需要的:-) –