2012-04-23 100 views
0

我使用下面的代碼通過使用jQuery ajax調用webservice。但它不起作用? webservice以JSON格式返回值。我如何通過此代碼訪問Web服務?如何使用jQuery與Ajax調用webservice?

<html> 
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> 
    <script> 
    $(document).ready(function() { 
     $('input[id^="button"]').click(function() { 
      alert('You have clicked ' + $(this).val()); 
      $.ajax({ 
       type: 'Get', 
       url: 'http://localhost:56789/xxx/Handler.ashx?key=yyy ', 
       success: function (data) { 
        alert(data); 
       } 
      }); 

     }) 
    }) 
    </script> 

    <body> 
     <div id="Sample_Div"> 
      <input type="button" id="button1" value="button1" /> 
     </div> 
    </body> 
</html> 
+0

這適用於我。你會得到什麼錯誤? – binarious 2012-04-23 12:22:44

+0

我沒有得到任何錯誤在同一時間沒有得到結果 – user 2012-04-23 12:25:05

+1

Javascript控制檯說什麼? – binarious 2012-04-23 12:27:35

回答

2

也許你可以試試這個。

$.ajax({ 
     url: "../Services/Person.asmx/SavePersonById", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     type: "POST", 
     data: '{ID:"00123"}', 
     success: function (response) { 
      //do whatever your thingy.. 
    } 
}); 

Web服務的東西:

[WebMethod] 
public string SavePersonById(string ID) 
    { 
    //do some code here.. 
    dbContext.Save(ID,"Firstname","Lastnmae"); 
    return "Successfully Saved!"; 
    } 
0

你可以試試這個:

$(document).ready(function() { 
    $('#button').click(function() { 
     $.ajax({ 
      type: "POST", 
      url: "appWebservices/select.asmx/checkLogin", 
      data: "{ ID:'" + $(this).val()+ "'}", 
      contentType: "application/json;charset=utf-8", 
      datatype: "json" 
     }); 
    }); 
}); 

編寫Web服務如下:

[WebMethod] 
public string checkLogin(string ID) 
{ 
    //Write your code here.. 
    //return value 
} 

know moredetails