用javascript向一个网页连接接口发送请求,并接收该接口返回的json串

一般前端与后端的互交都是通过json字符串来互交的,我的理解就是与网页接口的来回数据传递采用的数据结构就是json。一般是这样。

 

比如后端的代码是这样的:

 1 @RequestMapping(value = "quartz/list", method = RequestMethod.GET, produces = "application/json")
 2     public @ResponseBody String listQuartz(HttpServletRequest request, HttpServletResponse response) {
 3 
 4         response.setContentType("application/json");
 5 
 6         String json;
 7         List<DDSProduct> products = new ArrayList<DDSProduct>();
 8 
 9         try {
10 
11             conn = connPool.getConnection();
12 
13             Statement stmt = conn.createStatement();
14             // Create a result set object for the statement
15             ResultSet rs = stmt.executeQuery("SELECT jobID,filePath FROM NwfdDDSDetail");
16 
17             while (rs.next()) {
18                 DDSProduct product = new DDSProduct();
19                 product.setJobID(Integer.parseInt(rs.getString("jobID")));
20                 product.setFilePath(rs.getString("filePath"));
21 
22                 products.add(product);
23 
24             }
25             connPool.freeConnection(conn);
26 
27 
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31 
32         Gson g = new Gson();
33 
34         json = g.toJson(products);
35 
36         return json;
37 
38     }
View Code

由上面代码可以看出,后端Servlet的一个函数在接收到该网页的http的GET请求后,立即用JDBC向数据库取出了相关的信息,并转换成json字符串,向这个网页接口返回这个json串,如果前端不采取任何措施,这样的数据是让用户让用户看不懂的,前端的作用就是获取这些json数据,把他解析出来(js原生就支持解释json),根据js和html和CSS把它用适当的形式展现出来,这是一个前后端基本的互交流程.下面是一个前端请求后端数据并展现的一个过程:

 

 1 <html>
 2 <head>
 3  <title>Show Product List</title>
 4  <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"> 
 5  </script>
 6  
 7  
 8 </head>
 9 <body>
10 <h2>Hello World!</h2>
11 <div id="result" style="color:red"></div>
12 <script>
13 var getJSON = function(url) {
14       return new Promise(function(resolve, reject) {
15         var xhr = new XMLHttpRequest();
16         xhr.open('get', url, true);
17         xhr.responseType = 'json';
18         xhr.onload = function() {
19           var status = xhr.status;
20           if (status == 200) {
21             resolve(xhr.response);
22           } else {
23             reject(status);
24           }
25         };
26         xhr.send();
27       });
28     };
29 
30     getJSON('http://localhost:8080/MQDispatch/mq/quartz/list').then(function(data) {
31         alert('Your Json result is:  ' + data); //you can comment this, i used it to debug
32         
33         
34         var html = '<ul>';
35         for (var i = 0; i < data.length; i++) {
36             html += '<li>' + 'jobID is:'+data[i].jobID + ', file path is' +data[i].filePath + '</li>';
37         }
38         html += '</ul>';
39         
40         
41         document.getElementById('result').innerHTML = html; //display the result in an HTML element
42     }, function(status) { //error detection....
43       alert('Something went wrong.');
44     });
45 
46 </script>
47 
48 </body>
49 </html>
View Code

 

后端可以看到,js向该接口做出请求,并用回调函数取出了返回的数据,并把它解析为一个<ul>,放入div块中。之后还可以做更复杂的展示,这只是一个例子。

 

 

references:

http://stackoverflow.com/questions/9922101/get-json-data-from-external-url-and-display-it-in-a-div-as-plain-text

http://www.cnblogs.com/etindex/archive/2009/03/10/1408210.html

http://stackoverflow.com/questions/17620654/getting-data-from-a-json-url-and-displaying-it-in-html-with-javascript-jquery?rq=1

http://baike.baidu.com/link?url=7iy69iOZvqMJzn0aoytKsFCwr4pzXDDS_U-pStxdOd5EdSaCg_apCP7jXUqXme5rse463WOzqU9_flsh10d3G_     (jsonp百科)

http://baike.baidu.com/link?url=QdtzWyRqUDvO1zR9TI_YDGPf1baL73RB7j2ASd_abck2CJLgmvJeU1qm0zU1HdxFUhl4mv6_UsvJ_9jYo4TednOtZMgF3iOslwTxGYxbO_O  (Ajax百科)

https://www.quora.com/How-does-a-frontend-code-and-a-backend-code-interact-with-each-other

posted @ 2015-12-17 09:41  foo__hack  阅读(23236)  评论(0编辑  收藏  举报