Over: This code snippet shows how to call a web api from HTML5 using ajax. I am using JQuery Mobile with HTML5. The cPerson class is case sensitive on the client json side. You must uncomment System.Web.Script.Services.ScriptService in the webservice. A list of persons (1..n) can be returned, in this case only one person is returned. you can then cycle through the list by index. You should use asp.net 4.0 framework on the server.
Server Side
Define a class
public class cPerson
property sId as string
property sFirstName as string
property sLastName as string
end class
<System.Web.Script.Services.ScriptService()> _
...
<WebMethod()> _
Public Function GetList(sId As String) As List(Of cPerson)
Dim sql As String
Dim dr As OdbcDataReader = Nothing
Dim oList = New List(Of cPerson)
Dim oPerson As cGAR
Dim sql as string
sql="select firstname,lastname from persons where id=" & sId
Try
Using conn As OdbcConnection = New OdbcConnection(oFn.theODBCConnectionString)
conn.Open()
selectCommand = New OdbcCommand(sql, conn)
selectCommand.CommandTimeout = 0
dr = selectCommand.ExecuteReader
Do While dr.Read
oPerson = New cPerson
With oPerson
.sId = sId
.sFirstName = dr("firstname")
.sLastName = dr("lastname")
oList.Add(oPerson)
End With
Loop
dr.Close()
End Using
Catch ex As Exception
End Try
Return (oList)
End Function
Client Side
<ul data-role="listview" id="lbxGARList">
</ul>
<script type="text/javascript">
function GetData() {
var request = $.ajax({
type: "POST",
url: "http://yourwebserver/mywebservice.asmx/GetList",
data: "{ sId : '2' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
}
function OnSuccessCall(jsonData) {
var ul=$("#lbxList");
for (var index in jsonData.d) {
var sFirstName=jsonData.d[index].sFirstName.toString();
var sLastName=jsonData.d[index].sLastName.toString();
ul.append("<li><a href=''>" + sFirstName + ' ' + sLastName +"</a></li>");
ul.listview("refresh")
}
}
function OnErrorCall(x,y,z) {
//alert(response.status + " " + response.statusText);
alert(x + '\n' + y + '\n' + z);
}
$('#ajax_click').click(function () {
GetData();
});
</script>