2015-09-25 115 views
0

我正在使用jQuery .ajax()將一些值提交給db.php頁面,我從我的db中檢索其他記錄。我使用一個以對象形式返回查詢結果的類。我需要將該對象返回原始頁面並輸出。將對象值從php傳遞給jQuery

$.ajax({ 
    type: 'POST', 
    url: '/db.php', 
    data: { 
    'item': myItem 
    }, 
    dataType : 'json', 
    async: true, 
    success: function (response) { 

     // need returned values here 

    } 
}); 

db.php中

$results = $db->get_results(" 
    SELECT * 
    FROM t1 
    WHERE id = " . $id); 

// if I were to output my results here I'd do 
// foreach ($results AS $res) { 
//  $item = $res->item; 
// } 

echo '{ "res": '.$results.' }'; 

現在知道,如果我需要傳遞迴我的JS之前編碼什麼...

+3

PHP的'json_encode'是你的朋友。 – undefined

回答

1

怎麼樣json_encode()

echo json_encode($result); 

js:

success: function (response) { 

    console.log(response) 

    for(var i=0; i <response.length; i++){...} 

} 

編輯:請確保您添加application/json; charset=utf-8頭,如果不是你需要解析響應JSON.parse(response)

0

你可以做這樣的事情,結果:

echo json_encode(array(
'result' => $result, 
)); 

,並在您success: function(response)

success: function(response){ 
response = JSON.parse(response); 
console.log(response); 
}