2012-02-08 91 views
1

我正試圖在jquery中檢索我的php腳本中生成的以下json。但是,我無法顯示它。如果我提醒它,它只會顯示'未定義'。使用$('#demo').html(data.htmlOutput)來顯示html也不會執行任何操作。請有人指出我做錯了什麼?使用Jquery時無法顯示返回的JSON

$arr = array('htmlOutput' => '<b>hello</b>', 'no_rows' => 'balh'); 
echo json_encode($arr); 

$.post('get-offers.php', $("#offerForm").serialize(), function(data) { 
     alert (data.htmlOutput); 
     alert (data.no_rows) 
     $('#demo').html(data.htmlOutput); 
} 

我可以看到FB控制檯中的json響應,但它仍然沒有任何作用。

+0

該腳本如何知道將其解析爲JSON? – 2012-02-08 17:13:25

+0

@BarryChapman。它應該知道,請參閱下面的答案。 – gdoron 2012-02-08 17:23:03

+0

@gdoron - 我正在申請'重定向'。我希望他可能會意識到,他沒有告訴腳本,它期望JSON,並可以找到答案:) – 2012-02-08 17:23:59

回答

3
,你期待JSON

泰爾jQuery的,它的最後一個參數:

$.post('get-offers.php', $("#offerForm").serialize(), function(data) { 
     alert (data.htmlOutput); 
     alert (data.no_rows) 
     $('#demo').html(data.htmlOutput); 
}, "json"); 
2

你有期待json對象告訴jQuery的,與數據類型做如下:

.post('get-offers.php', $("#offerForm").serialize(), function(data) { 
     alert (data.htmlOutput); 
     alert (data.no_rows) 
     $('#demo').html(data.htmlOutput); 
},'json'); //<==== 

數據類型:類型從服務器預期的數據。

docs

,我覺得jQuery將能猜出它是一個json對象,因爲在他們的文檔寫的:

默認:智能猜測(XML,JSON,腳本,文本,html)。

嗯,我猜這猜是不是智能...... =)

0

兩個選項:

首先,設置 'JSON' 爲你$.post最後一個參數告訴它它期待着一個JSON響應。

其次,你的第一個警報之前,補充一點:

var obj = jQuery.parseJSON(data); 

然後alert(obj.htmlOutput);

看看是否能爲你工作

+0

第二個選項是多餘的... – gdoron 2012-02-08 17:27:00