嗨,我的 setDefaultPoint Controller 以 json 形式返回 map ...代码如下
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
}
向该 Controller 发送请求的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 中我传递了两个不同的对象..那么如何获取这些对象的属性...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
参数将是解析自的 JavaScript 对象返回的json字符串,只要该字符串是有效的json即可。 ajax 调用中传递的数据不需要括号。这应该有效
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);
}
});
}
关于jquery - 如何使用 jquery/javascript 处理 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7089368/