簡體   English   中英

如何將參數從prototypejs客戶端傳遞到REST Web服務

[英]How to pass parameter from prototypejs client to rest web service

我有一個像這樣的休息網絡服務

@Path("/postItem")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Item postItem(@QueryParam("name") String name, @QueryParam("price") String price)
{
  System.out.println(name);
  System.out.println(price);
  return new Item(name , price);
}

我使用prototypejs javascript lib從客戶端使用以下代碼片段調用上述REST Web服務。

<script>
  new Ajax.Request('/some_url', {
    method:'post',
    parameters: {name: 'apple', price: 12}
    onSuccess: function(transport) {
    var response = transport.responseText || "no response text";
    alert("Success! \n\n" + response);
    },
    onFailure: function() { alert('Something went wrong...'); }
 });
</script>

問題:我無法正確將參數傳遞給服務方法的名稱和價格。

我在客戶端傳遞了兩個參數,但是在服務端僅映射了參數“名稱”(值也錯誤)。 當我打印名稱和價格時,我得到以下內容

 System.out.println(name);  ==> name='apple'&price=12
 System.out.println(price); == null

我如何將參數傳遞給prototypejs客戶端的服務,以便“名稱”獲得值apple,“價格”獲得值12。

在“名稱”周圍加上引號,即

之前

    parameters: {name: 'apple', price: 12}

    parameters: {'name': 'apple', 'price': 12}

“名稱”最有可能是在對象中未正確傳遞的關鍵字

編輯

還有更多嘗試的方法...

  • 確保您使用的是最新的PrototypeJS版本1.7.1

  • parameters: {name:'apple',price:12},后添加逗號parameters: {name:'apple',price:12},

  • 再次檢查瀏覽器是否使用Chrome Dev Tools或Firebug正確傳遞了參數-如果正確傳遞了參數,請檢查您的后端腳本

好的,最后它通過修改url起作用了。

<script>
   new Ajax.Request('/some_url?name=apple&price=12', {
   method:'post',
   onSuccess: function(transport) {
   var response = transport.responseText || "no response text";
   alert("Success! \n\n" + response);
 },
   onFailure: function() { alert('Something went wrong...'); }
});
</script>

您可能想嘗試的一些選項:

將參數作為轉換為查詢字符串的JS對象傳遞:

ajaxParameters = Object.toQueryString({ qkey: qValue });

其中qkey和qValue是字符串。 在作為對象的Ajax.Request的第二個參數中,使用所得的ajaxParameters作為參數值。

PrototypeJS Hash對象在大多數情況下也可以正常工作:

ajaxParameters = $H({ qKey0: qValue0, qKey1: qValue2 [, ...]  });

該方法是否為POST應該沒有問題。 有時POST方法也可能具有帶有“ GET”變量的ACTION(url),例如

HTTP://mydomain.net/post.php?id=n&action=z

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM