grails - 在remoteFunction属性中使用变量值

时间:2012-01-03 23:18:27

标签: grails

[请开始评论以查看此问题的当前位置,谢谢。希望快速/易读通过]

我遇到了渲染模板的情况,模板有一个javascript函数需要通过remoteFunction向控制器动作发送正确的值,例如:下面:

<script type="text/javascript">
  function updateOrderEntry() {
    alert("updating OrderEntries");
    var unused = ${remoteFunction(action:'userByName', id:userId, update:[success: 'userOrderList', failure: 'userOrderListError'])};
  }
</script>

我收到警报并且打电话&#34;当在页面上执行此函数时,控制器正常,但它没有发送id值(params不包含id)。当我构建模板时,我提供userId作为模型参数,并且我已经验证它使模板很好(例如在div中)。

我尝试了上述的一系列变体,但无法使其发挥作用,例如:使用remoteFunction作为标记:

 var unused = <g:remoteFunction action="userByName" id="${userId}" update="[success: 'userOrderList', failure: 'userOrderListError']" />;

我还尝试了使用params属性的各种风格(这会更好),但是在没有让它工作之后,我想我会尝试让id参数工作。

当我尝试变量填充remoteFunction属性时,我做错了什么?

由于

[项目在Grails 1.3.7上]


--------------------------------更新每第1 /第2条评论--------- --------------------------

此控制器没有URL映射,但删除了另一个控制器的URL映射。另外 注释掉 我在此控制器中的beforeInterceptor调试,即:

  // def beforeInterceptor = [action: this.&debug]

  // def debug() {
  //  println "ACTION: ${actionUri}, PARAMS: ${params}"
  // }

我在调试代码中添加了userByName操作的顶部,即:

 def userByName = {
    println "action: ${actionUri}, params: ${params}"

我还做了3个版本的remoteFunction,它从模板中的控制器发回,所有 3相同,除了 ,第二个版本使用的是userId硬编码,而不是由变量产生,即:

 function updateOrderEntry() {
    alert("updating OrderEntries, 1st time");

    var unused = ${remoteFunction(action:'userByName', id:userId, params:[userId:userId], update:[success: 'userOrderList', failure: 'userOrderListError'])};

    alert("updating OrderEntries, 2nd time, THIS TIME WITH hardcoded id and param values");
    var unused = ${remoteFunction(action:'userByName', id:'4', params:[userId:'4'], update:[success: 'userOrderList', failure: 'userOrderListError'])};

    alert("updating OrderEntries, 3rd time, back to non-hard-coded values");
    var unused = ${remoteFunction(action:'userByName', id:userId, params:[userId:userId], update:[success: 'userOrderList', failure: 'userOrderListError'])};
}

当此功能发送回浏览器时(从渲染模板),浏览器(Chrome,使用其网络调试)显示它收到:

   function updateOrderEntry() {
    alert("updating OrderEntries, 1st time");

    var unused = jQuery.ajax({type:'POST',data:{'userId': '4'}, url:'/nameIsInAppPropsFile/money/userByName/4',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

    alert("updating OrderEntries, 2nd time, THIS TIME WITH hardcoded id and param values");
    var unused = jQuery.ajax({type:'POST',data:{'userId': '4'}, url:'/nameIsInAppPropsFile/money/userByName/4',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

    alert("updating OrderEntries, 3rd time, back to non-hard-coded values");
    var unused = jQuery.ajax({type:'POST',data:{'userId': '4'}, url:'/nameIsInAppPropsFile/money/userByName/4',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;
}

所有这些看起来都和我一模一样。 updateOrderEntry()会自动被调用,我会看到所有3个警报,如上所示。相应地,在服务器上,我看到以下调试输出:

action: /money/userByName, params: [userId:null, action:userByName, controller:money]
action: /money/userByName, params: [userId:4, id:4, action:userByName, controller:money]
action: /money/userByName, params: [userId:null, action:userByName, controller:money]

问题是,第1和第3个远程功能中的userId或id没有正确设置(如服务器所示),不清楚为什么会这样。有些东西是不同的,只是无法弄清楚是什么。

P.S。 Chrome和Firefox的结果相同。


------根据以下评论3 - 5更新--------------------------

看看Chrome发送的内容,中间的好请求如下:

 Request URL:http://localhost:8080/nameIsInAppPropsFile/money/userByName/4
 Request Method:POST
 Status Code:200 OK
 Request Headersview source
 Accept:*/*
 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
 Accept-Encoding:gzip,deflate,sdch
 Accept-Language:en-US,en;q=0.8
 Connection:keep-alive
 Content-Length:8
 Content-Type:application/x-www-form-urlencoded
 Cookie:JSESSIONID=F0FDCEE323A1834350E209A7C211E64D
 Host:localhost:8080
 Origin:http://localhost:8080
 Referer:http://localhost:8080/nameIsInAppPropsFile/money/transaction
 User-Agent:Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7
 X-Requested-With:XMLHttpRequest
 Form Dataview URL encoded
   userId:4

2个不好的(注意第1行和最后一行,以及?)是:

 Request URL:http://localhost:8080/nameIsInAppPropsFile/money/userByName
 Request Method:POST
 Status Code:200 OK
 Request Headersview source
 Accept:*/*
 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
 Accept-Encoding:gzip,deflate,sdch
 Accept-Language:en-US,en;q=0.8
 Connection:keep-alive
 Content-Length:11
 Content-Type:application/x-www-form-urlencoded
 Cookie:JSESSIONID=F0FDCEE323A1834350E209A7C211E64D
 Host:localhost:8080
 Origin:http://localhost:8080
 Referer:http://localhost:8080/nameIsInAppPropsFile/money/transaction
 User-Agent:Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.7 (KHTML, like Gecko)  Chrome/16.0.912.63 Safari/535.7
 X-Requested-With:XMLHttpRequest
 Form Dataview URL encoded
   userId:null

因此,这显示了浏览器发送的内容不同。

当我硬编码我给模板的值时,即模型:[....,userId:&#39; 4&#39;],我得到了相同的失败结果。在我使用之前:model:[....,userId:order.user.id],但是我更新了我的调试输出并确认了硬编码&#39; 4&#39;这里没有帮助。


更新:添加与实际代码匹配的最小测试用例。注意:真实代码是一个包含3个部分的页面,顶部是固定的,其中选择了客户;中间部分更新了该客户的订单;底部显示通过订单关联的信用卡交易,通常是多个(例如授权,捕获,无效等)。当用户在底部交易部分中执行操作(例如,无效)时,不仅需要更新此部分,还需要更新中间部分部分。我试图获得订单部分 - &#34; 第二 div&#34; - 使用底部事务部分上的link / remoteFunction进行更新,并在其onComplete处理程序中调用将执行第二个remoteFunction的Javascript函数,以使中间部分更新。

下面是一个最小的测试用例,我无法准确地重现问题,但有趣地发现了一个不同但相关的问题。看来Grails(或者某种方式是IntelliJ,我的IDE)在remoteFunction中指定的id参数存在问题,当它在Javascript中时。当你运行它时,你会明白我的意思。希望快速复制代码并运行。感谢。

----一些简单的控制器,无需模型----

 class UiTestController {

   static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

  def index = {
    println "rendering remoteTest"
    render(view: 'remoteTest')
  }

  def section1 = {
    println "action1 params: ${params}"

    render(template: 'remoteSection1', model: [id: params.id])
  }

  def section2 = {
    println "action2 params: ${params}"
    render(template: 'remoteSection2', model: [id: params.id])
  }
}

--- remoteTest.gsp -

 <%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
   <title>Remote</title>
   <g:javascript library="jquery" plugin="jquery"/>
</head>
<body>

   <div style="text-decoration:underline; color:purple; cursor:pointer; margin: 20px"
    onclick="${remoteFunction(action: 'section1', id:'1', update: 'section1')}">click to update section 1</div>
   <br />
   <div id="section1">1st Section to Update</div>
   <br />
   <div id="section2">2nd Section to Update</div>
  </body>
</html>

---- _remoteSection1.gsp -----

  <g:javascript library="jquery" plugin="jquery"/>

 <div>
     <p>Section 1 updated, (id=${id}). Now, similar to real code, we
     <span style="text-decoration:underline; color:purple; cursor:pointer;"
          onclick="${remoteFunction(action: 'section2', id: '2', update: 'section2')}">update section 2</span>
    </p>
 </div>

---- _remoteSection2.gsp -----

 <g:javascript library="jquery" plugin="jquery"/>

 <script type="text/javascript">
     function updateSection1() {
        alert("doing remoteFunction with fixed value 55");
        var unused = ${remoteFunction(action: 'section1', id='55', update: 'section1')};
        alert("doing remoteFunction with fixed value 65, using params");
        var unused = ${remoteFunction(action: 'section1', params:[id:'65'], update: 'section1')};
  } 
  </script>

  <div>
      <p>Section 2 updated, (id=${id}). Now, similar to real code, we
      <span style="text-decoration:underline; color:purple; cursor:pointer;"
          onclick="${remoteFunction(action: 'section2', id: '2', update: 'section2', onComplete: 'updateSection1()')}">update section 2 again, and also section 1 with javascript updateSection1() function</span>
     </p>
  </div>


FINAL UPDATE


代码正在运行,变更原因未知。我不得不继续执行其他一些任务,而且我已经回到了这个任务,我的控制器发生了变化,令人惊讶的是事情正在发挥作用。和以前一样的Javascript调用。但是我会很快发布它,以防你之前发现某种混乱:

-------------------------- _moneyEntries.gsp中的相关Javascript代码-------------- ------------

  function updateOrderEntry() {
    alert("Updating OrderEntries --  1st time");
    ${remoteFunction(action:'userByName', id:userId, update:[success: 'userOrderList', failure: 'userOrderListError'])};

    alert("Updating OrderEntries -- 2nd time, THIS TIME WITH hardcoded id and param values");
    ${remoteFunction(action:'userByName', params:[id: '4'], update:[success: 'userOrderList', failure: 'userOrderListError'])};

    alert("Updating OrderEntries -- 3rd time, back to non-hard-coded values");
    ${remoteFunction(action:'userByName', params:[id: userId], update:[success: 'userOrderList', failure: 'userOrderListError'])};

 }

----------------谷歌网络视图向我展示了什么 - 整个回复--------------

<script type="text/javascript" src="/nameIsInAppPropsFile/plugins/jquery-       1.6.1.1/js/jquery/jquery-1.6.1.js"></script>

<script type="text/javascript">

    function confirmVoid(moneyTransId) {
       return confirm("Void transaction ID " +moneyTransId + ":");
    }

   function confirmCredit(moneyTransId, amountIn) {
     var valid = false;
     var amount = amountIn;
    while (!valid) {
        var r = prompt("For ID " +moneyTransId+ ", please specify the amount:", amount);
        if (r == null || r == "") {
            valid = true;
            amount = -1;
        } else {
            //alert("result is:" +r);
            if (r > amount) {
                alert("You cannot credit an amount greater than " + amount);
                amount = amountIn;
            }
            else {
                amount = r;
                // invoke remote function, update result
                valid = true;
            }
        }
    }
    return amount;
}

function confirmCapture(moneyTransId) {
    return confirm("Capture funds for ID " +moneyTransId + ":");
}

function confirmSend(moneyTransId) {
    return confirm("Are you sure you want to send an email receipt for ID " +moneyTransId + ":");
}
    //var unused = jQuery.ajax({type:'POST', url:'/nameIsInAppPropsFile/money/userByName/3',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

function updateOrderEntry() {
    alert("Updating OrderEntries --  1st time");
    jQuery.ajax({type:'POST', url:'/nameIsInAppPropsFile/money/userByName/8',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

    alert("Updating OrderEntries -- 2nd time, THIS TIME WITH hardcoded id and param values");
    jQuery.ajax({type:'POST',data:{'id': '4'}, url:'/nameIsInAppPropsFile/money/userByName',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

    alert("Updating OrderEntries -- 3rd time, back to non-hard-coded values");
    jQuery.ajax({type:'POST',data:{'id': '8'}, url:'/nameIsInAppPropsFile/money/userByName',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});;

}


 </script>

 <div>
    <div style="margin-bottom:9px;">Order # 1005 Merchant Transactions:
    <span class="jsAction" style="padding-left:30px"
          onclick="jQuery.ajax({type:'POST',data:{'userId': '8'}, url:'/nameIsInAppPropsFile/money/userByName',success:function(data,textStatus){jQuery('#userOrderList').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}});; return false;">(refresh order status)</span></div>
<div class="list">
    <table>
        <thead>
        <tr>
            <th>What Action?</th>
            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=id&amp;order=asc">ID</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=dateCreated&amp;order=asc">Date</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=type&amp;order=asc">Transaction Type</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=responseCode&amp;order=asc">Result</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=totalAmt&amp;order=asc">Amount</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=description&amp;order=asc">Description</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=txid&amp;order=asc">Authorize.Net Transaction Id</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=responseReasonText&amp;order=asc">Authorize.Net Response Text</a></th>

            <th class="sortable" ><a href="/nameIsInAppPropsFile/money/voidTrans/12?sort=ccNumber&amp;order=asc">Credit Card #</a></th>

        </tr>
        </thead>
        <tbody>

            <tr class="odd">

                <td>
                   <!-- First Check for transaction validity, for it to be 'actionable' -->

                      none

                   </td>


                <td>13</td>

                <td>01-13-12 03:41 MST</td>

                <td>VOID OF previous authorization, ID 12</td>

                <td><span class="">
                        Approved</span></td>

                <td>NA</td>

                <td>Void: sfk .</td>


                <td>2168161109</td>

                <td><span class="">
                    This transaction has been approved.</span></td>

                <td></td>

            </tr>

            <tr class="even">

                <td>
                   <!-- First Check for transaction validity, for it to be 'actionable' -->
                   none
                   </td>


                <td>12</td>

                <td>01-13-12 03:41 MST</td>

                <td>AUTHORIZATION ONLY - then Voided in ID 13</td>

                <td><span class="">
                        Approved</span></td>

                <td>$11</td>

                <td>sfk .</td>


                <td>2168161109</td>

                <td><span class="">
                    This transaction has been approved.</span></td>

                <td>x9113</td>

            </tr>

        </tbody>
    </table>
   </div>

   <!--div class="paginateButtons">

   </div-->
 </div>

-------------------------- Debug输出在控制器中显示的内容-----

 ACTION: /money/userByName, PARAMS: [id:8, action:userByName, controller:money]
 ACTION: /money/userByName, PARAMS: [id:4, action:userByName, controller:money]
 ACTION: /money/userByName, PARAMS: [id:8, action:userByName, controller:money]

所以,我不知道它为什么现在正在工作,而不是之前。但updateOrderEntry()是一样的。也许你之前看到我做错了什么,在这种情况下请告诉我。再次感谢您对Tomasz的帮助,我学到了很多能够使用Google Chrome进行调试(感谢您的帮助)。

2 个答案:

答案 0 :(得分:1)

它对我来说很好,Grails 2.0,我设置了def userId = 7,你可以看到它出现在URL中:

            function updateOrderEntry() {
                alert("updating OrderEntries");
                var unused = jQuery.ajax({type:'POST', 
                    url:'/controller/userByName/7',
                    success:function(data,textStatus)
                        {jQuery('#userOrderList').html(data);},
                    error:function(XMLHttpRequest,textStatus,errorThrown)
                        {jQuery('#userOrderListError').html(XMLHttpRequest.responseText);}
            });;}        

答案 1 :(得分:0)

这就是params在remoteFunction中的工作原理:

....
params:'\'id=\'+document.getElementById(\'idField\').value',
.....
相关问题