2012-02-01 59 views
2

林Doiung錯了嗎?PHP Zend框架的JSON解碼用ajax失敗

感謝所有幫助

編輯:

香港專業教育學院嘗試過:

$.ajax({ 
url: STValentines.baseUrl+'/mensaje/sendmessage', 
type: 'POST', 
dataType: 'json', 
data: {userId: '111', imageUrl: 'imageurl', message: 'message' }, 
success: callBack 
}); 

同樣的錯誤

編輯2:

這裏再次js代碼PHP代碼和結果:(

$.ajax({ 
     url: 'testURL', 
     type: 'POST', 
     dataType: 'json', 
     data: "{'userId': 'test1234', 'imageUrl': 'testimageUrl', 'message': 'testmessage' }", 
     success: callBack 
    }); 


public function sendmessageAction() { 
    $data = $this->_request->getPost(); 
    print_r($data); 
    $response = $data; 
$this->_helper->json($response); 

結果:

Array 
(
) 
+0

是您的正確格式的JSON字符串? – 2012-02-01 21:31:11

+0

'$ data'實際上是否包含JSON字符串? PHP的本地'json_decode()'工作嗎? JSON字符串中是否有多字節/非ASCII字符? – Carpetsmoker 2012-02-01 21:31:41

+0

請看我的編輯 – gruber 2012-02-01 22:00:14

回答

1

乍一看,它看起來像你發送可能是不正確的數據。如果我沒有記錯的話,需要引用對象屬性。嘗試這個。

$.ajax({ 
    url: 'testURL', 
    type: 'POST', 
    dataType: 'json', 
    data: {"userId": userIds, "imageUrl": imageUrl, "message": message }, 
    success: callBack 
}); 
+0

沒有工作:/相同的錯誤 – gruber 2012-02-01 22:07:06

+0

什麼是PHP接收?你可以發佈一個'print_r($ data);'給我們看結果嗎? – Crashspeeder 2012-02-01 22:14:19

+0

看看我的編輯 – gruber 2012-02-01 22:32:17

3

Crashspeeder至少在他的數據格式中應該是正確的。

從PHP手冊 - json_decode - 解碼JSON字符串

//correct json format 
Example #1 json_decode() examples 


<?php 
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 

var_dump(json_decode($json)); 
var_dump(json_decode($json, true)); 

?> 

實施例#使用json_decode()

<?php 

// the following strings are valid JavaScript but not valid JSON 

// the name and value must be enclosed in double quotes 
// single quotes are not valid 
$bad_json = "{ 'bar': 'baz' }"; 
json_decode($bad_json); // null 

// the name must be enclosed in double quotes 
$bad_json = '{ bar: "baz" }'; 
json_decode($bad_json); // null 

// trailing commas are not allowed 
$bad_json = '{ bar: "baz", }'; 
json_decode($bad_json); // null 

?> 
3常見的錯誤

也可以使用...

json_last_error - 返回上次發生錯誤

得到錯誤。

+1

我認爲問題是$ data = $ this - > _ request-> getPost();返回一個數組而不是字符串,這就是爲什麼Zend_Json :: decode($ data,true);拋出一個錯誤:( – gruber 2012-02-02 09:10:01

+0

@gruber True,但$ this_request-> getPost('data')應該有一個json字符串,或者你可以試試$ this - > _ request-> getRawBody(),它返回原始的post數據。 – RockyFord 2012-02-02 15:39:35

0

我建議如下:

  1. 從AJAX請求刪除dataType: 'json'
  2. 在操作中,使用return $this->_helper->json($responseArray);。無需更改佈局或任何東西。
+1

任何新的Zend框架開發人員都面臨同樣的問題:) – palAlaa 2012-05-23 07:54:35