从jquery post返回二维数组

时间:2013-11-04 19:25:02

标签: jquery

我正在绞尽脑汁,我需要通过jquery发送一个搜索值来在数据库中进行全文搜索,然后将其显示在div元素中。我需要在Category表和SubCategory表中搜索值。我想不出来,我认为最好的是如果我发布两次(首先搜索类别,第二次搜索子类)。函数search_fulltext返回二维数组。

我在考虑这样的事情(我知道它不起作用,但只想展示我希望它如何工作,我不知道如何处理二维数组)

// 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>

1 个答案:

答案 0 :(得分: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'
});