Grails:Ajax参数未到达控制器

时间:2014-06-10 20:42:34

标签: javascript jquery ajax grails

我的GSP中有一个按钮,如下所示:

<button id = "select"
    onclick = "${remoteFunction(controller: 'customer', 
                                action: 'selectBatch',
                                params: '\'batchID=\' + selectedBatchID')}">
Select
</button>

一切都很顺利&批次ID&#39;参数很好地到达了我的控制器,但我意识到每次按下按钮时我都不想调用此函数,只有在满足某些条件时才会这样。所以,我重新定义了我的按钮:

<button id = "select" >Select</button>

并将其绑定到这样的javascript函数:

$('#select').click(function () {
    if (selectedBatchID == undefined) {
        $("#errorMessages p").text("Click a row to choose a batch first.");
        $("#errorMessages p").show();
        $("#errorMessages p").fadeOut(3000);
    }
    else {
        validBatchID = selectedBatchID;
        $("#choosebatch h2").text("Batch ID " + selectedBatchID + ": " + selectedBatchDesc);
        $('#AdminConsole p').css("font-size", "30px");
        $("#AdminConsole p").html("Batch ID " + selectedBatchID + "<br />" + selectedBatchDesc);
        console.log(selectedBatchID);
        $.ajax({
               type: 'POST',
               url: "${createLink(action:'selectBatch', controller:'customer')}/batchID=" + selectedBatchID
        });
    } 
});

现在看来这个变量并没有达到我的控制器功能,如下所示:

def selectBatch = {
    println "Batch ID: " + params.batchID
    selectedBatch = Batch.findWhere(id: params.batchID.toInteger())
    println "Batch selected: " + selectedBatch
}

因为我的控制器抱怨:

............Batch ID: null
Error |
2014-06-10 16:27:54,686 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver  -         NullPointerException occurred when processing request: [POST] /FatcaOne_0/customer/selectBatch    /batchID=35
Cannot invoke method toInteger() on null object. Stacktrace follows:
Message: Cannot invoke method toInteger() on null object

这就是Chrome调试器显示的内容:

35 VM725:78
POST http://hostname/FatcaOne_0/customer/selectBatch/batchID=35 500 (Internal Server     Error) jquery.tools.min.js:38
send jquery.tools.min.js:38
f.extend.ajax jquery.tools.min.js:38
(anonymous function) VM725:79
f.event.dispatch jquery.tools.min.js:37
h.handle.i

所以我们可以看到它不是空的,因为它打印了值&#39; 35&#39;在Chrome调试器中,但是为什么控制器没有看到这一点,特别是当它也包含在由Ajax调用形成的URI中时?

2 个答案:

答案 0 :(得分:1)

改变&#39; /&#39;到&#39;?&#39;:

${createLink(action:'selectBatch', controller:'customer')}/batchID=

${createLink(action:'selectBatch', controller:'customer')}?batchID=

如果你正在使用grails 2.x.x,你也可以写:

def selectBatch (Integer batchID) {
    ...
}

答案 1 :(得分:1)

尝试将$.ajax替换为:

$.ajax({
    url: "${createLink(controller: 'customer', action: 'selectBatch')}",
    type: 'POST',
    data: {batchID: selectedBatchID}
});      
相关问题