2015-09-25 114 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); 
}