jquery - Ajax 调用不会通过 GRAILS Controller 上的 withFormat->json

标签 jquery grails

我有一个 gsp 页面,其中包含一个执行 ajax 调用的 JS 函数(名为“sample”)。

function sample() {
         var params = { office: {id: "testId"}, population: {id: "testId2"}};

        $.ajax({
            url: "http://localhost:8080/officeProj/mustache/list",
            cache: false,
            contentType: "application/json; charset=utf-8",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(params),
            complete:function(json){
                console.log(" reponse :"+ json);
            },
            success: function(officeData) {
                var template = "<h1>{{data.firstName}} {{data.lastName}}</h1>";
                var html = Mustache.to_html(template, data);
                $('#sampleArea').html(html);
            } ,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("error :"+XMLHttpRequest.responseText);
            }
        })

    }

现在,这个 ajax 调用到达适当的 GRAILS Controller 和适当的操作,定义为:

def list = {

    withFormat {
        html { return [title: "Mustache" , data:[firstName:"Indiana", lastName:"Jones"], address:"NYC" ] }
        json {
            // extract the data to be rendered to the page
            println("processing JSON.....")
            render ([title: "Mustache" , data:[firstName:"Indiana", lastName:"Jones"], address:"NYC" ] as JSON)
        }
    }
}

问题是控件从不经过 Controller 操作中的 withFormat->json ,因此我没有看到预期的结果。(当控件返回到 gsp 页面时,它会经过“完整的”,但不是通过“成功”。没有记录错误。任何人都可以看到我的 ajax 调用有任何问题吗?如果我需要提供更多信息,请告诉我。提前致谢。

最佳答案

尽管您的问题似乎已经解决,但我想提一下背后的实际原因。

问题似乎出在 grails 进行内容协商的方式上。

根据grails文档,grails将查找接受 header ,这将决定响应格式。

但是这里的问题是,默认情况下,在 config.groovy 中,grails.mime.use.accept.header = false,它基本上忽略了接受头,所以即使你在你的文件中设置了 dataType:"json"ajax 请求(依次将接受 header 设置为“application/json”),它不会查找接受 header ,并且响应格式将始终为“all”,这是默认值。

所以基本上设置 grails.mime.use.accept.header = true 就可以解决问题。

希望这有帮助

关于jquery - Ajax 调用不会通过 GRAILS Controller 上的 withFormat->json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405049/

相关文章:

jquery - 尝试 "sync"2 html 表格(应用列宽)

javascript - 将子 div 动画到父 div 的中心

php - 使用纯 jquery/javascript 创建弹出确认框

javascript - 使用ajax和php更新数据库

hibernate - Hibernate HQL:两个级别的联接

ajax - 使用 Ajax 验证 Grails 命令对象

javascript - 将 jquery 与用户脚本结合使用

grails - Grails中类[]的属性[]不能为null错误

grails - Bootstrap.groovy中的自定义JSON不为域返回此类属性错误

Grails 2.2.0 URLMappings : Any way to use same URL with Different Verb