2010-10-28 83 views
1

我想在php中解碼JSON我使用javascript(jquery)中的ajax調用發送。Json在PHP解碼

的JavaScript代碼:

var editSchedule_data = { 
     'action'   : 'editSchedule', 
     'eventid'   : $('#eventid').val(), 
     'pixels_per_minute' :$('#pixels_per_minute').val(), 
     artists: { 
      artist: [] 
     } 
    } 

    $('.artist').each(function(index) { 
     var id=$(this).attr('id'); 
     id=id.split('_'); 
     editSchedule_data.artists.artist.push({ 
      'artistid' : id[0], 
      'stageid'  : id[1], 
      'left'  : $(this).offset().left-$('.artists').offset().left, 
      'width'  : $(this).width() 
     }); 
    }); 

    $.ajax({ 
     type : "POST", 
     url : "callback.php", 
     data : editSchedule_data, 
     dataType : "json", 
     async : true, 
     success : function(json) { 
      if(json.success) { 
       showSucces(json.message); 

      } 
      else{ 
       showError(json.message); 
      } 
     }, 
     error: function(error){ 
      alert("An error occurred: "+error.message); 
     } 
    }); 

在PHP-代碼:

$clean = sanitize($_POST); 

echo(json_encode($clean['artists']), 
json_last_error()); 

echo(json_decode($clean['artists']), 
json_last_error()); 

我的輸出: 編碼:

{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]} 
0 

解碼:

0 

有人能告訴我如何讓解碼功能工作?

+0

'$ decoded_json = json_decode($ clean ['artists']); var_dump($ decoded_json);'? – 2010-10-28 08:58:24

回答

2

你爲什麼試圖在那裏使用json_decode?你已經有數據作爲$ _POST中的數組了。這就是爲什麼json_decode失敗並且返回NULL ...它需要一個正確的格式化字符串,並且你正在向它傳遞一個數組。 如果dataType:「json」參數使您感到困惑,它將指定您期望從服務器返回的數據的類型,而不是指定要發送的數據的類型。 您應該簡單地處理$ _POST中的數據,創建您的響應,在其上應用json_encode並回顯結果字符串。

1

json_decode($clean['artists']);給你一個對象,這就是爲什麼回顯它不顯示任何東西。嘗試print_r(),看看有什麼物體內部:

// Will show you the whole PHP object 
print_r(json_decode($clean['artists'])); 
+0

print_r(json_decode($ _ POST ['artists'])); switch(json_last_error()) case JSON_ERROR_DEPTH: echo' - 超過最大堆棧深度'; 休息; case JSON_ERROR_CTRL_CHAR: echo' - 發現意外的控制字符'; 休息; case JSON_ERROR_SYNTAX: echo' - 語法錯誤,格式錯誤的JSON'; 休息; case JSON_ERROR_NONE: echo' - 沒有錯誤'; 休息; } 給我: 警告:json_decode()預計參數1是字符串數組中 給出的 - 沒有錯誤 – Vincent 2010-10-28 09:42:40

1

這是好多了,如果你會使用這個。從數據庫

$.getJSON("callback.php",function(json){ 
$('#div to update').html(json[0].databasefield); // 0 if query is only 1 result 
});         // when there are many of them use for loop 

在你的PHP讀取數據時,你應該使用json_encode(數組值)進行編碼;