2014-12-01 69 views
-1

這是結果:[{ 「APN」: 「173-76-001」}]如何將JSON結果的值獲取到標籤中?

從這個代碼(PHP):

<?php 
require_once('../config.php'); 

if(isset($_GET['parcel_id'])) { 
    $db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); 
    $data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']); 
    if($data != null) echo json_encode($data); 
    //if ($data != null) echo $data; 
} 
?> 

的jquery:

 $('#searchTable tr').click(function(){ 
      var parcel_id = $(this).attr('id'); 
      alert(parcel_id); 
      $.ajax({ 
       url: "classes/get-apn.php?id=" + parcel_id, 
       //timeout: 30000, 
       type: "GET", 
       error: function(SMLHttpRequest, textStatus, errorThrown){ 
        alert("An error has occurred making the request: " + errorThrown); 
       }, 
       success: function(data){ 
        //do stuff here on success 
        alert(data); 
        $('#ParcelNumber').val(data);    
       } 
      }); 
     }); 

如何我是否將apn(173-76-001)的價值轉化爲標籤?

即時通訊新事物,所以感謝您的幫助提前! :)

編輯:所以我嘗試了下面的迴應,但它沒有奏效。我被告知我需要使用jQuery.parsJSON進行解析,但它也不起作用。我很困惑。這裏是我更新的jQuery代碼:

 $('#searchTable tr').click(function(){ 
      var parcel_id = $(this).attr('id'); 
      $('#ParcelId').html(parcel_id); 
      $.ajax({ 
       url: "classes/get-apn.php?id=" + parcel_id, 
       //timeout: 30000, 
       type: "GET", 
       data: { parcel_id : parcel_id }, 
       dataType: 'json', 
       error: function(SMLHttpRequest, textStatus, errorThrown){ 
        alert("An error has occurred making the request: " + errorThrown); 
       }, 
       success: function(data){ 
        //do stuff here on success 
        var result = $.parseJSON(data); 
        alert(result.apn); 
       } 
      }); 
     }); 

回答

1

您執行ajax請求到服務器。服務器查詢數據庫並將輸出格式設置爲json。 Ajax請求特此成功,下面的代碼行設置標籤的值:

$('#ParcelNumber').val(data); 

標籤這裏ID爲ParcelNumber。要獲得價值,你可能需要:

$('#ParcelNumber').val(data[0]["apn"]); 

無論ParcelNumber是不是「價值」的控制(例如,不是input但固定的div),使用.html方法:

$('#ParcelNumber').html(data[0]["apn"]); 
+0

我改成了'$ ('#ParcelNumber')。val(data [「apn」]);'現在我的頁面壞了:( 是[{「apn」:「173-76-001」}]數組結果?看起來很奇怪好像有一個太多的括號 – maryjane 2014-12-01 15:54:20

+0

哦,對不起,我錯過了一個數組,請看看更新的答案。順便說一句,括號裏面的意思是「數組由一個元素,元素是apn = ...「 – mudasobwa 2014-12-01 15:57:14

+0

我會試一試。我完全只是打破了我的頁面,我不知道如何:( – maryjane 2014-12-01 16:09:56