2012-07-06 43 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