如何使用jquery / javascript处理Json

时间:2011-08-17 07:43:57

标签: jquery ajax json grails

我的setDefaultPoint控制器将map作为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}}

4 个答案:

答案 0 :(得分:4)

由于返回的dataType指定为json,因此传递给分配给data的函数的success参数将是从返回的json字符串解析的JavaScript对象,只要string是有效的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);
        }

    });
}

答案 1 :(得分:1)

var obj = jQuery.parseJSON(data);

然后您可以访问obj.class等内容。

文档: http://api.jquery.com/jQuery.parseJSON/

答案 2 :(得分:1)

如果您设置了dataType: "json",则只需在成功回调中parseJSON

alert(data.class);

答案 3 :(得分:1)

因为您已将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)         
        }

    }); 
}