PDA

View Full Version : Can't seem to bind ajax data to grid



kashim
28 Nov 2011, 8:21 AM
My server method returns data that looks like this


{ "d": [{ "__type": "Agent", "AgentID": 1, "FirstName": "Joe", "LastName": "Bloggs" },
{ "__type": "Agent", "AgentID": 2, "FirstName": "John", "LastName": "Smith" }
]}


when I try to bind it to a grid using the following code I get the error


Ext.Error: Unable to parse the JSON returned by the server: You're trying to decode an invalid JSON String:


//model
Ext.define('AgentModel', {
extend: 'Ext.data.Model',
fields: [{ name: 'AgentID' }, { name: 'FirstName' }, { name: 'LastName'}]
});


//store
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: 'AgentModel',
proxy: {
type: 'ajax',
url: '../WebSite_JSON/WebService.asmx?GetAgents',
reader: {
type: 'json',
root: 'd'
}
}
});


//grid
var grid = Ext.create('Ext.grid.Panel', {
title: 'Get Agents from Website_JSON',
store: store,
columns: [
{ text: 'agent_id', dataIndex: 'AgentID' },
{ text: 'first_name', dataIndex: 'FirstName' },
{ text: 'last_name', dataIndex: 'LastName' }
],
width: 420,
height: 300,
renderTo: Ext.getBody()
});

btw
my grid is happy to bind to the data like this



var data = { "d": [{ "__type": "Agent", "AgentID": 1, "FirstName": "Joe", "LastName": "Bloggs" },
{ "__type": "Agent", "AgentID": 2, "FirstName": "John", "LastName": "Smith" }
]};


//step1 datastore
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: 'AgentModel',
data: data,
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'd'
}
}
});

i also tried to do the binding in the success handler of an Ajax request (but that didnt work either)




any ideas anyone
thanks
kashim

tvanzoelen
28 Nov 2011, 8:29 AM
Did you set the contenttype on the Seervers Response?



response.ContentType = "text/javascript";


Can you post a firebug response from that url?

jratcliff
28 Nov 2011, 8:37 AM
You can also put a breakpoint in ext-n.n.n/src/data/reader/Json.js in the getResponseData method to see what it sees as the responseText

kashim
1 Dec 2011, 4:32 AM
sorry for the delay

I think my store syntax defining the proxy is wrong because when I call the same url using Ajax.request class its ok...ie


Ext.Ajax.request({ url: '../WebSite_JSON/WebService.asmx/GetAgents',
method: 'GET',
headers: { 'Content-Type': 'application/json;charset=utf-8' },
success: function (response) {
var data = Ext.decode(response.responseText);


// var data is good! and looks like how i've shown it in original post


}
});

Can this ajax request be defined into the store's proxy definition?

tia
kashim

jratcliff
5 Dec 2011, 7:16 AM
Can this ajax request be defined into the store's proxy definition?

Well, looking at the docs you can see that 'headers' is a property you can set on the proxy. Have you tried it to see if it works?

http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.Ajax-cfg-headers