2016-02-05 44 views
0

我開發了下面的代碼,它從數據庫中獲取數據。獲取文本數據以及ajax成功的json數據

//get number of stores for zip code 
    $numberofstores = $resultstore = mysqli_query($conn, "SELECT store,address FROM geoinfo WHERE zipcode = '$search_text'"); 
    //get values from db 

    $addressArray = Array(); 
    $storeArray = Array(); 

    while ($row = mysqli_fetch_array($resultstore, MYSQL_ASSOC)) { 
    $storeArray[] = $row['store']; 
    $addressArray[] = $row['address']; 
} 
    //return data to the client 
    echo json_encode($addressArray); 
    echo json_encode($storeArray); 


    $total = mysqli_num_rows($resultstore); 
    if(mysqli_num_rows($resultstore) != 0) { 
    echo "".$total." store/s found within this area";  

這裏是我的Ajax調用,

$(function() { 

$('#form_geocode').on('submit', function (e) { 
      e.preventDefault(); 

      $.ajax({ 
      type: 'post', 
      url: 'controller.php', 
      dataType: 'text', 
      data: $('#form_geocode').serialize(), 
      success: function (data) { 
      for (var x = 0; x < data.length; x++) { 

      $("#location_results").html(data[x]+"<br>"); 


     } 

     } 
      }); 

     }); 

    }); 

在成功輸出,

["226 N LARCHMONT BLVD, LOS ANGELES, CA","670 S WERN AVE, LOS ANGELES, CA","3201 W 6TH ST, LOS ANGELES, CA"]["RITE AID PHARMACY","RALPHS","WALGREENS?"]3 store/s found within this area  

我的問題是我怎麼能提取2個陣列成js和存儲文本獨立的2個陣列請幫助。

回答

1

很簡單,在JSON編碼之前將3個元素組合成一個更大的數組;

變化

echo json_encode($addressArray); 
echo json_encode($storeArray); 

echo "".$total." store/s found within this area"; 

echo json_encode(array($addressArray, $storeArray, "".$total." store/s found within this area"));  
+0

感謝。沒關係。但是我怎樣才能分別打印3個元素的數組。該代碼沒有提供任何內容。請看我編輯的代碼。 –

+0

簡單地將數據類型更改爲json –

+0

事實上 - 數據類型JSON,則返回的JSON的頂層將包含3個JSON元素(addressArray,storeArray和總字符串)。 –