Have been used a lots of jquery in the recent real-time information web development project, I found this quite easy to initiate a POST HTTP call to web service through JQuery. Here are 2 sample code snippets.
Case 1: Pass no parameter
<script type="text/javascript">
// in this case, we post nothing back to api but
// just call it (no parameter required) and expected json object as result
function callWebApiViaPost() {
$.ajax({
type: "POST",
url: "yourwebapi",
data: "{}",
contentType: "application/json;",
dataType: "json",
success: function (t) {
$("#your_result_display_div").text(t.d);
}
});
}
</script>
Case 2: Pass parameter(s)
For example, you have a API like below:
[WebMethod]
public static string ToUpperCase(string yourparam)
{
return yourparam.ToUpper();
}
The corresponding jquery ajax post call will be like this:
<script type="text/javascript">
// in this case, we post nothing back to api but
// just call it (no parameter required) and expected json object as result
function callWebApiViaPost() {
$.ajax({
type: "POST",
url: "yourweb/ToUpperCase",
data: "{yourparam: 'hello-world'}",
contentType: "application/json;",
dataType: "json",
success: function (t) {
$("#your_result_display_div").text(t.d);
}
});
}
</script>
No comments:
Post a Comment