2015-07-05 103 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它的工作... –

相关问题