2012-07-06 42 views
0

我得到通過PHP這些結果在我的AJAX警報如何提醒我的json結果?

[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] 

我該怎麼做$('#divid').html(message);提醒?

我只想從json數組中指定值。

下面是代碼

function showMessage(id){ 
      var dataString = 'id=' + id; 
        $.ajax( 
        { 
         type: "POST", 
         url: "/inbox/instshow", 
         data: dataString, 
         success: function(results) 
         { 

          if(results == "error") 
          { 
           alert('An error occurred, please try again later. Email us with the issue if it persists.'); 
          } 

          if(results != "notallowed" && results != "error" && results != "login") 
          { 

           alert(results); 
           alert(results[0].message); 

          } 
         } 
        }); 

     } 
+1

我們可以看到您用於通過ajax獲取數據的代碼: – 2012-07-06 03:42:49

+0

編輯該問題以顯示我的代碼。 – Darius 2012-07-06 04:05:57

回答

5
data = [{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] 


$('#divid').html(data[0].message); 

DEMO

您可能需要使用解析一個jQuery.parseJSON JSON字符串。

// results is your JSON string from the request 
data = jQuery.parseJSON(results); 
$('#divid').html(data[0].message); 
+0

由於某種原因,它說undefined當我alert(results [0] .message);但是當我提醒(結果)時;它顯示data = [{「message_id」:「3」,「box」:「0」,「from_id」:「3」,「to_id」:「1」,「title」:「Hello先生! 「:」你好嗎?「,」sender_ip「:」「,」date_sent「:」「,」status「:」0「}] – Darius 2012-07-06 03:50:46

+0

http://api.jquery.com/jQuery.parseJSON/? – Mahn 2012-07-06 03:53:43

+0

@Darius然後你有一個JSON編碼的**字符串**,你需要使用jquery.parseJSON解析(Mahn提供的鏈接) – sachleen 2012-07-06 04:06:56

1

使用JSON.stringify()功能

var data=[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] ; 
alert(JSON.stringify(data)); 
1

這裏是你的數據按級別劃分:

[ 
    { 
     "message_id":"3", 
     "box":"0", 
     "from_id":"3", 
     "to_id":"1", 
     "title":"Hello sir!", 
     "message":"how are you?", 
     "sender_ip":"", 
     "date_sent":"", 
     "status":"0" 
    } 
] 

你可以使用數據[0] .message因爲第一級表示數組,因此需要[0]引用第一個和唯一的元素,第二個是對象,哪些屬性可以通過object.member語法訪問。

1

用於調試

的console.log(數據,data.message, 「無所謂」)

你需要打開Firebug或Safari的督察,並期待在 「控制檯」

4

如果ajax你應該包括:

dataType: 'json' 

代碼

$.ajax( 
     { 
      type: "POST", 
      url: "/inbox/instshow", 
      data: dataString, 

      dataType: 'json', // here 

      success: function(results) { 

      } 

......... 

包括這個jQuery的將解析返回的數據爲JSON自動爲您(不需要任何手工解析工作),你會得到你的結果你現在正在嘗試。

+0

謝謝你,非常感謝。 – Darius 2012-07-06 05:52:55