Can I Consume WebAPI using JQuery/AJAX, in plain HTML file?
What do I need in order to consume in plain HTML file? i.e. reference to specific jquery/ajax javascript library etc.
1) It gives me javascript error at below line.
Error: $jQuery is undefined
Line: $jQuery.support.cors = true;
Am I missing some javascript reference?
2) If I remove above line, it goes straight into error function and shows me following message.
ERROR: Could not retrieve the data\n
I tried to access my web api service in browser and it does return JSON data to me.
http://localhost:29604/api/Region[
^]
Below is the data I am able to receive in browser:
[{"RegionID":1,"RegionDescription":"Eastern "},{"RegionID":2,"RegionDescription":"Western "},{"RegionID":3,"RegionDescription":"Northern "},{"RegionID":4,"RegionDescription":"Southern "}]
Any help?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web API Client (using JQuery/AJAX) for Region</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<h2>Web API Client (using JQuery/AJAX) for Region</h2>
<script type="text/javascript" >
function GetRegion() {
alert('inside GetRegion():');
$jQuery.support.cors = true;
$.ajax({
type: "GET",
url: "http://localhost:29604/api/Region",
dataType: "json",
contentType: "json",
success: function (data) {
WriteResponse(data);
alert('success:');
},
error: function (x, y, z) {
alert('ERROR: Could not retrieve the data\n');
}
});
}
function WriteResponse(Region) {
var strResult = "<table><th>ID</th><th>Description</th>";
$.each(Region, function (index, Region) {
strResult += "<tr><td>" + Region.RegionID + "</td><td> " + Region.RegionDescription + "</td></tr>";
});
strResult += "</table>";
$("#outputData").html(strResult);
}
function ShowRegion(Region) {
if (Region != null) {
var strResult = "<table><th>ID</th><th>Name</th><th>Description</th>";
strResult += "<tr><td>" + Region.RegionID + "</td><td> " + Region.RegionDescription + "</td></tr>";
strResult += "</table>";
$("#outputData").html(strResult);
}
else {
$("#outputData").html("No Results To Display");
}
}
</script>
<div>
<table>
<tr>
<td>
<button onclick="GetRegion();">Get Regions</button></td>
</tr>
</table>
</div>
<div id="outputData" class="scroll" style="text-align: center;"></div>
</body>
</html>