2011-10-05 17 views
0

我已经创建了这样的代码来访问我的webservice中的方法AddNums。我通过webservice发送数据来获取输出。但它没有提供任何输出。webserivce从我的jquery调用

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <script src="scripts/Jquery%20v1.6.4.js" type="text/javascript"></script> 
    <script type="text/javascript"> 

    $(document).ready(function() { 
    $("#btn").click(function() { 
     alert('I have been clicked'); 
     $.ajax({ 
      type: "POST", 
      url: "http://localhost:5554/Service1.svc", 
      data: "{2,3}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (msg) { 
       $("#output").text(msg.d); 
      } 
     }); 

    }); 
    }); 

    </script> 
    <head runat="server"> 
    <title></title> 
    </head> 
    <body> 
    <form id="form1" runat="server"> 

     <input type="button" id="btn" value="Click Me" /> <br /> <br /> 

     <span id="output"></span> 

     </form> 
     </body> 
     </html> 

webserivce的实现。我已经在Visual Studio中使用内置客户端测试了webservice,它工作正常。

namespace WcfServiceTest 
    { 

    [System.Web.Script.Services.ScriptService] 
    public class Service1 : IService1 
    { 
    public string GetData(int value) 
    { 
     return string.Format("You entered: {0}", value); 
    } 

    public CompositeType GetDataUsingDataContract(CompositeType composite) 
    { 
     if (composite == null) 
     { 
      throw new ArgumentNullException("composite"); 
     } 
     if (composite.BoolValue) 
     { 
      composite.StringValue += "Suffix"; 
     } 
     return composite; 
    } 

    [System.Web.Services.WebMethod(BufferResponse = false)] 
    public int AddNums(int val1, int val2) 
    { 
     return (val1 + val2); 
    } 

    } 
    } 
+0

你真的需要这个可怕的空白在你的文件名?在这种情况下,人们通常使用'_'或'-'或'.'。 – ThiefMaster

+0

我对ASP不是很熟悉,所以我可能是错的,但是不应该在POST'val1 = 1&val2 = 2'而不是JSON? –

+0

输出结果时不应该只使用'msg'而不是'msg.d'? (文件).ready(function(){(“#btn”)。click(function(){ alert('I have been clicked)( –

回答

1

这是错误的方式

data: "{2,3}", 

正确的方法是

data: {para1:value1,para2:value2}, 

的参数传递到外部文件。

+0

)嗨,我做了更改,即使它不工作。 '); $ .ajax({type:“POST”, url:“http:// localhost:5554/Service1.svc/AddNums”, data:'{val1:“2”,val2:“3 “}', contentType:”application/json; charset = utf-8“, dataType:”json“, 成功:函数(msg){$(”#output“).text(msg.d); } }); }); }); – dotnetrocks

+0

我在你的代码中看到的问题是你在单引号中包装数据参数是不需要的。也不需要URL参数分号。 val1和val2已经成为post变量,因为您正在使用post请求,因此请在您的服务器文件中获取这些变量,如 $ _POST ['val1']等等。 –