2015-07-05 99 views
1

我有一個wcf服務運行,其中包含一個返回字符串的方法。我能夠成功地在瀏覽器中運行服務。此外,我甚至可以傳遞所需的參數,並可以在瀏覽器中看到結果。如何從JavaScript客戶端傳遞參數給WCF Rest服務的方法?

但是,當我試圖從javascript客戶端調用相同的方法參數值不傳遞給該方法,因此它不返回任何內容。

這裏是我的服務retuns從瀏覽器 enter image description here

跑這裏來當我的接口實現:

[OperationContract] 

      [WebInvoke(Method = "GET", 
      ResponseFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Wrapped)] 
      string JSONData(string id); 

這裏是我的服務方法的實現代碼:

public string JSONData(string id) 
    { 
     if (id == null || id == "") 
     { 
      return "Id is null"; 
     } 
     else 
     { 
      return "You requested product " + id; 
     } 
    } 

由於上面顯示的服務工作正常罰款參數從URL傳遞。然而,當我撥打電話使用jQuery的函數參數不列入獲得通過這裏是我的JavaScript客戶端的代碼

<script type="text/javascript"> 
     // A $(document).ready() block. 
     $(document).ready(function() { 
      // alert("pass"); 
      var valu = "123"; 
      $("#btnclick").click(function() { 
       debugger; 
       $.ajax({ 
        cache: false, 
        type: "GET", 
        async: false, 
        url: "http://localhost:35798/RestServiceImpl.svc/JSONData", 
        data: JSON.stringify(valu), 
        contentType: "application/json", 
        dataType: "json", 
        success: function (result) { 
         var ans = JSON.stringify(result); 
         alert("success"); 
         alert(ans); 
        }, 
        error: function (xhr) { 
         alert("error"); 
         alert(xhr.responseText); 
        } 
       }); 
      }); 
     }); 

    </script> 

我希望能夠從jQuery代碼傳遞參數。任何建議,以獲得這項工作將非常感激。

回答

1

VALU需要是一個關鍵值對:

var valu = {id:"123"}; 

或字符串:

var value = 'id="123"'; 

爲了目前形成適當的請求。

在第一種情況下將它作爲一個普通的JavaScript對象傳遞,不要將其串化。如果你做jQuery會將它作爲字符串追加到請求中。

在瀏覽器中使用網絡調試工具來解決這些問題。

這將正確連載你的查詢字符串/JSONData?id=123,而不是你的解決方案產生/JSONData/"123"

你有編輯的代碼...

<script type="text/javascript"> 
    // A $(document).ready() block. 
    $(document).ready(function() { 
     // alert("pass"); 
     var valu = {id: "123"}; 
     $("#btnclick").click(function() { 
      debugger; 
      $.ajax({ 
       cache: false, 
       type: "GET", 
       async: false, 
       url: "http://localhost:35798/RestServiceImpl.svc/JSONData", 
       data: valu, 
       contentType: "application/json", 
       dataType: "json", 
       success: function (result) { 
        var ans = JSON.stringify(result); 
        alert("success"); 
        alert(ans); 
       }, 
       error: function (xhr) { 
        alert("error"); 
        alert(xhr.responseText); 
       } 
      }); 
     }); 
    }); 

</script> 
+0

非常感謝它的工作就像一個魅力.. :) –

+0

@Gdroid:我從代碼項目中獲得了與服務完全相同的代碼,並嘗試將jquery複製到空白客戶端頁面html中,並在正文部分保留了Rober的正確jQuery代碼。我是ASP.NET新手請幫助我如何確保它運行?我在WCF解決方案中創建了這個頁面,這個頁面從codeproject – Learner

+0

下載,你可以在瀏覽器中運行html頁面,然後使用F12鍵打開Element Inspector窗口,然後在控制檯標籤下,你可以找到你得到的響應,如果它說200它的工作... –

相關問題