2013-03-05 156 views
0

我有一個簡單的Ajax調用PHP的JSON響應。我多次寫過這些內容,但從未遇到過這個問題。ajax JSON返回null

Ajax通過「id」參數發送罰款,PHP收到它,它是否工作並返回json響應,這是問題開始的地方。其中一個參數始終爲空,因爲我似乎無法找到的原因。我已經手動測試了PHP,並且它返回了這兩個值。我已經檢查過ajax,看看它是否恢復了id參數。所以這個問題是在json響應被髮送的地方,jquery ajax接收到的。

// This gets the paramaters from the url 
theParams = parseURLParams(document.URL); 

// ^^ it returns an id, like this {"id":"4a17bcb93fe3fac3978671a66959d902"} 

$.ajax({ 
    url: 'viewer_code.php', 
    type: 'GET', 
    dataType: 'json', 
    data: {id: theParams.id}, 
    success: function(dataImg) { 

    alert(dataImg.imgUrl); 

    } 
}); 

和PHP(一切似乎罰款&都將被消毒)

$id = $_GET['id']; 

    $q = "SELECT * FROM `images` WHERE id = '$id'"; 
    if(!($result_set = mysql_query($q))) die(mysql_error()); 
     $row = mysql_fetch_array($result_set); 

     $thumb = $row['thumb']; 
     $image = $row['image']; 

     header('Content-Type: application/json'); 
     echo json_encode(array("imgUrl" => $image, "id" => $id)); 

當PHP是手動測試,它返回:{ 「imgUrl的」: 「照片/ 75de7c1c30d956113f937a8e685f7e50.jpg」 「id」:「4a17bcb93fe3fac3978671a​​66959d902」}

這是總是返回null的imgUrl,任何人都知道爲什麼會發生這種情況? 哦,我已經嘗試從GET切換到POST,因爲以前的問題已經建議,但它沒有任何區別。

提前非常感謝您的幫助,歡呼傢伙:)

+0

你有沒有嘗試過使用print_r或其他東西來回應數組的值,而不是將它作爲json發送,以確保ajax請求獲得正確的值。 – Pitchinnate 2013-03-05 16:44:32

+0

您正在使用[an **過時的**數據庫API](http://stackoverflow.com/q/12859942/19068)並應使用[現代替換](http://php.net/manual/en/ mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻擊](http://bobby-tables.com/)**,現代的API會使[防禦]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己從。 – Quentin 2013-03-05 16:47:26

回答

1

你有沒有使用id: 1我有一個很大的問題試圖處理那些不正確的JSON變量嘗試id: theParams.id代替。

在另一方面,我做了類似的代碼,但沒有

header('Content-Type: application/json'); 

有你在你的PHP文件echo json_encode(array("imgUrl" => 'image.jpg', "id" => '1'));嘗試根據這些測試也許我可以幫助你更

+0

似乎沒有幫助,但我會通過一些測試運行,並將它們放在這裏: – 2013-03-05 17:08:51

+0

測試一:輸出:改變回聲json_encode(array(「imgUrl」=> $ image,「id」=> $ id) ); to:echo json_encode(array(「imgUrl」=>「image.jpg」,「id」=> $ id)); < - 沒有工作,所以可能沒有輸出?現在運行另一個測試 – 2013-03-05 17:10:26

+0

只需運行一個測試,當我拿走DataType時返回的內容:'json'。這回來了: {「imgUrl」:null,「id」:[「4a17bcb93fe3fac3978671a​​66959d902」]} < - 可能與[]有關? – 2013-03-05 17:15:54