jquery - 如何使用 jquery/javascript 处理 Json

标签 jquery ajax json grails

嗨,我的 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/

相关文章:

html - PHP/JQuery/AJAX,一些初期问题

ios - iOS 中 JSON 解析中的 TableView 中未显示图像

javascript - 如何循环遍历json数组以获取javascript中的值

c# - 需要有关 MVC 中 AJAX 表单流程的建议

jquery - 在页面加载和更改时使用 AJAX 填充 SELECT 元素

java - Jersey json 序列化错误记录在哪里?

jquery - 莫里斯图年 x 轴

jQuery 和 CSS - 如何阻止相关元素左右浮动(滚动时)?

javascript - 数学游戏 JQuery/JavaScript

php - Ajax PHP 创建的表单未提交