2014-02-10 22 views
0

我想使用ajax()函數將JSON變量和整數發送到頁面並追加檢索到的數據。這是我在此刻:jQuery - 如何進行ajax POST調用並追加數據

$.ajax({ 
    type: "POST", 
    dataType: "json", 
    url: "get_theme.php", 
    data: {themestack:themes, iterator:theme_max_iterator}, 
    success: function(data){ 
     alert('Items added'); 
     $("#themes").append(data); 
     ++IFRAMES_IN_DOM; 
     ++theme_max_iterator; 
    }, 
    error: function(e){ 
     alert(e.message); 
    } 
}); 

themesJSON變量,theme_max_iteratorint。目前,我收到的只是"undefined"的提醒,所以我想知道什麼是錯的?

編輯:

在日誌文件中,我可以看到從get_theme.php錯誤:

PHP Warning: json_decode() expects parameter 1 to be string, array given 

導致這種結果是該行:

$obj = $_POST['themestack']; 
$json_data = json_decode($obj, true); 

因爲JSON這是奇怪的變量themestackJSON

+0

它可能會去錯誤的功能。所以你的'get_theme.php'返回一個錯誤 – anurupr

+0

檢查你的get_theme.php是否發送了正確的響應。 – Abhidev

回答

0

我覺得你越來越在json_decode()array嘗試encode json第一則decode像,

$obj = $_POST['themestack']; 
if(is_array($obj)){// check if obj is an array then encode it first 
    $obj = json_encode($obj); 
} 
$json_data = json_decode($obj, true); 

或者通過你的data使其json像以前一樣,

data: {themestack:JSON.stringify(themes), iterator:theme_max_iterator}, 
0

它看起來像你在你的錯誤中發出警報:回調......我建議看看請求/響應以查看服務器返回的內容。

或者,您可以將alert(e.message)更改爲alert(JSON.stringify(e))以瞭解它告訴您的內容。但提到的第一件事可能比這個後面的更具信息性,更接近這個問題。

0

如果你的AJAX期待JSON數據,你必須呼應使用「json_encode」在該php

<?php 
    $result = "blah blah" 
    echo json_encode($result); 
    ?> 
0

我認爲你的themes是一個數組。所以,當你在PHP中使用$_POST['themestack']時,你有一個數組。而jason_decode(...)函數需要一個JSON字符串作爲參數。

也許你應該更改以下行:

data: {themestack:JSON.stringify(themes), iterator:theme_max_iterator}, 

或者,也許你並不需要jason_decode()和$_POST['themestack']對象你想要什麼。你可以把它看作一個數組,並像$_POST['themestack'][0]那樣訪問它。