如何使用jquery / javascript处理Json
您好我的setDefaultPoint控制器将地图作为json返回…代码如下
def setDefaultPoint = { if (springSecurityService.isLoggedIn()) { def officeId = params.officeId def officeRoleInstance=OfficeRole.get(officeId) def company= officeRoleInstance.company def defaultPoint = officeRoleInstance.distanceChart.officePoint def map = [defaultPoint:defaultPoint] map << [company:company] def json = map as JSON render json }
向该控制器发送请求的ajax调用是
function setDefaultPoint(){ var officeId = $('#clientTrip_officeId').val(); $.ajax({ url:"${createLink(controller:'clientTrip',action:'setDefaultPoint')}", dataType: "json", data:({officeId: officeId}), success: function(data) { // here i want to get the id and name of default point and id and name of company... console.log('id of defaultpoint is---"+????) console.log('name of default point is---"+????) console.log(id of company is-----------"+?????) } }); }
从json我传递两个不同的对象..所以如何获得这些对象的propirties … defaultPoint对象和Company对象都有名为id和anme的字段
响应看起来像
{"defaultPoint":{"class":"com.springpeople.steer.trips.Point","id":3,"name":"MG road"},"company":{"class":"com.springpeople.steer.partymodel.parties.Company","id":5,"addressPermanent":{"class":"Address","id":3},"contactDetails":null,"name":"Infosys","offices":[{"class":"OfficeRole","id":6}],"organizationRoles":[{"class":"OrganizationRole","id":5}],"panNumber":null,"serviceTaxNumber":null,"tanNumber":null}}
由于返回的dataType被指定为json
,因此传递给分配给success
的函数的data
参数将是从返回的json字符串解析的JavaScript对象,只要该字符串是有效的json即可。 在ajax调用中传递的data
不需要围绕它的parens。 这应该工作
function setDefaultPoint(){ var officeId = $('#clientTrip_officeId').val(); $.ajax({ url:"${createLink(controller:'clientTrip',action:'setDefaultPoint')}", dataType: "json", data: { officeId: officeId }, success: function(data) { console.log(data.defaultPoint.id, data.defaultPoint.name); console.log(data.company.id, data.company.name); } }); }
var obj = jQuery.parseJSON(data);
然后你可以访问像obj.class
这样的东西。
文件: http : //api.jquery.com/jQuery.parseJSON/
如果你设置了dataType: "json"
你就不需要在你的成功回调中只需要parseJSON
alert(data.class);
因为您已将dataType指定为Json,所以jQuery会将响应解析为对象,因此您应该能够使用:
function setDefaultPoint(){ var officeId = $('#clientTrip_officeId').val(); $.ajax({ url:"${createLink(controller:'clientTrip',action:'setDefaultPoint')}", dataType: "json", data:({officeId: officeId}), success: function(data) { // here i want to get the id and name of default point and id and name of company... console.log(data.defaultPoint.Id) } }); }