来自服务器的数据变为JSON数组,因为responseText是ajax请求:
Price : [{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]
Name : [{"id":"1","name":"P1"},{"id":"2","name":"P2"},{"id":"3","name":"P3"}]
我在Prototype中看到了这种方法:var json = transport.responseText.evalJSON(true);
我如何才能获得Price数组,因此JSON等于:
[{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]`
答案 0 :(得分:1)
php需要包含json标头:
header('Content-type: application/json');
ajax请求需要包含evalScripts(确保您信任源):
new Ajax.Request("json.php",
{ method: 'get',
parameters: {'xyz': 'json', 'var2': 'some_val'},
evalScripts: true,
onSuccess: function(response){your_function(response);}});
然后你的函数可以得到如下的json:
your_function = function (response) {
var result = response.responseJSON;
...
}
编辑:还有来自源的这些说明: http://www.prototypejs.org/learn/json
Edit2:以下是更新服务器的方法:
$return_data = array();
$return_data['price'] = getPrice($db);
$return_data['name'] = getName($db);
echo json_encode($return_data)."\n";
执行此操作后,在js中您可以执行以下操作(来自上面的your_function示例):
alert ("first id is: " + result['price'][0]['id']);