Under the MVC jquery ajax call through webapi

If that

jquery application, not of their own to fill.

Mvc create a project, the new controller, view the following:

 

 Where the data controller is responsible for the front desk to provide data, home access controller is a simple page controller.

data controller code as follows:

1 public class DataController : Controller
2     {
3         [HttpGet]
4         public ActionResult GetById(int id)
5         {
6             id++;
7             return Content(id.ToString());
8         }
9     }

Very simple, as a WebAPI, sent in a digital, plus a return.

Return content class also mentioned, I forgot to read a book on the action of the return type controller.

index page code is as follows:

 1 @{
 2     Layout = null;
 3 }
 4 
 5 <!DOCTYPE html>
 6 
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11 </head>
12 <body>
13     <div id="div1">
14         <input type="text" id="test1" /><br />
15         <input type="text" id="test2" value="0" /><br />
16         <input type="button" id="test3" value="提交" onclick="justdo()" />
17     </div>
18     <script src="~/jquery-3.4.1.min.js"></script>
19     <script language="javascript">
20         function justdo() {
21             $.ajax(
22                 {
23                     url: "/Data/getbyid/" + $("#test2").val(),
24                     type: "get",
25                     success: function (result) {
26                         $("#test2").val(result);
27                     }
28                 });
29         }
30         $(document).ready(function () {
31             setInterval(justdo, 3000);
32         });
33     </script>
34 </body>
35 </html>

Button, the timer can trigger ajax request justdo in, refresh the page contents.

operation result:

 

 keep changing:

 

 In this case the one hand, put a bit in jquery ajax usage, mainly to show a modern generic data transfer mode --webapi.

If the new mvc project no view, but in other forms (string, etc., json string particularly common) returns the results of the individual application needs, it can be used as "application program interface web page called" an existence, that is, webapi.

Note that, if webapi and call it something that is not within the same Web site, you need to set "homologous" can go online to find information.

Guess you like

Origin www.cnblogs.com/wanjinliu/p/11856502.html