2011-10-05 15 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']等等。 –