我正在从PHP生成JSON响应,它看起来像这样:
{ done:'1', options: [{ message:'Example message'},{message:'This is the 2nd example message'}]}
我想用ExtJS获取这些结果。这就是我到目前为止所知道的:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"}
});
接下来我要写什么才能得到这样的json结果:
var mymessages = jsonData.options;
并且mymessages应该包含示例消息,这是第二个示例消息。
谢谢。
发布于 2009-06-03 13:56:48
简单的方法:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(resp) {
// resp is the XmlHttpRequest object
var options = Ext.decode(resp.responseText).options;
Ext.each(options, function(op) {
alert(op.message);
}
}
});
或者,您可以使用Store以一种更具Ext风格的方式来实现:
var messages = new Ext.data.JsonStore({
url: 'myfile.php',
root: 'options',
fields: [
{name: 'text', mapping: 'message'}
],
listeners: {
load: messagesLoaded
}
});
messages.load({params: {id: "1"}});
// and when loaded, you can take advantage of
// all the possibilities provided by Store
function messagesLoaded(messages) {
messages.each(function(msg){
alert(msg.get("text"));
});
}
再举一个例子来说明最后一条评论:
var messages = [{title: "1"},{title: "2"},{title: "3"}];
var titles = msg;
Ext.each(messages, function(msg){
titles.push(msg.title);
});
alert(titles.join(", "));
虽然我更喜欢使用Array.map (Ext没有提供):
var text = messages.map(function(msg){
return msg.title;
}).join(", ");
alert(text);
发布于 2012-06-12 19:02:57
检查这个样例小提琴,它用于ExtJS4. http://jsfiddle.net/mrigess/e3StR/
Ext4以后使用Ext.JSON.encode()
和Ext.JSON.decode()
;而Ext3使用Ext.util.JSON.encode()
和Ext.util.JSON.decode()
发布于 2009-06-03 14:15:55
如果您确定您的输入是正确的(注意xss攻击),您可以使用eval()函数从您的json结果创建javascript对象,然后可以通过您的命令访问该对象:
var mymessages = jsonData.options;
但话又说回来,Ext为您做得很好,正如Rene通过Ext.decode函数指出的那样
https://stackoverflow.com/questions/944871
复制相似问题