2012-02-11 36 views
0

我正在使用ajax的相冊。相冊 - jquery ajax json + php

js代碼:

$(document).ready(function(){ 
    $('#next').click(function(){ 

    var next = $('#id').text(); 

    $.ajax({ 
     type: 'GET', 
     url: 'URL', //This I changed for this post 
     dataType: 'json', 
     data: { "id" : next}, 
     success: function(data){ 
      alert(data.error); 
      if(data.error == true) 
      { 
       alert(data.msg); 
      } 
      else 
      { 
      $('#pics').attr({ 
       src : data.src, 
       witdth : data.width, 
       height : data.height}); 
      $('#id').text(data.id); 
      } 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus +' ' + errorThrown); 
     } 
    }); 
    }); 
}); 

php文件的代碼:

if(is_integer($_GET['id'])) 
{ 
$error = false; 
$next = $_GET['id'] + 1; 

switch($_GET['id']) 
{ 
    case 1: $jsondata = '{"src" : "picture 01 valid path", '; 
      $jsondata .= '"width" : xxx, '; 
      $jsondata .= '"height" : xxx, '; 
      $jsondata .= ' "id" : '.$next; 
     break; 
    case 2: $jsondata = '{"src" : "picture 02 valid path", '; 
      $jsondata .= '"width" : xxx, '; 
      $jsondata .= '"height" : xxx, '; 
      $jsondata .= ' "id" : '.$next; 
     break; 
    ...+cases... 
    default: $jsondata = '{"msg" : "An error occured. Please close the tab and enter again. Thanks."'; 
      $error = true; 
} 

$jsondata .= ', "error" : '.$error.'}'; 

echo json_encode($jsondata, true); 
} 

HTML代碼: ‹上IMG SRC = 「有效的路徑」 寬度= 「XXX」 HEIGHT = 「XXX」/&rsaquo ;

與鉻的JavaScript控制檯的錯誤是'錯誤'爲空。我一直在網上嘗試很多組合和可能性,但沒有取得任何成功!你能幫助我嗎?

在此先感謝!

PS:我仍然不知道,如果這個解決方案將通過相冊瀏覽:s表示回答這個後的其他問題..

+0

使用Chrome的檢查器或Firebug檢查響應。確保一個有效的對象回來並且存在「數據」。並用'console.log(data);'替換alert(data.error);'看看它是否是一個有效的對象。 – Richard 2012-02-11 19:18:20

回答

0

您正在創建你的PHP代碼中的JSON字符串,所以你不要有編碼它。

從您的php代碼中刪除此行echo json_encode($jsondata, true);,然後嘗試使用echo $jsondata

0

你不需要做json_encode,所以echo $ jsondata應該足夠了