跨域调用Ajax生成Jquery Table和Bootstrap table-

为了测试用HTML直接访问Server端数据,然后生成Table, 特意试用了Jquery table和bootstrap table.
前端使用了HTML, Jquery, jquery.dataTables, bootstrap-table.具体见index.html中的引入包。由于是跨域访问, 使用了dataType: "jsonp",并且在后端代码设置了响应头允许ajax跨域访问。
jquery tables由于直接使用了Ajax, 所以相对简单。
Bootstrap table,没有找到直接使用jsonp的参数,就先使用ajax拿到数据,在把数据传给 bootstrapTable。

后端使用Nodejs.  nodejs的使用方法,请自行查阅。这里只记录一下我们要使用的程序启动命令:E:\test\nodejs\src>node service.js
启动后可以在浏览器看看返回的JSON内容 http://localhost:8081/listUsers   
由于有三个例子, 就做了三份json文件,供返回使用。JSON文件用success_jsonpCallback包裹起来,因为是使用了jsonp。

1.index.html

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4 <meta charset="utf-8"/>
  5 <title>Backend Data Table Testing</title>
  6     <!-- Jquery JS引用 -->
  7     <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  8 
  9     <!-- Bootstrap table JS引用 -->
 10     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.css" type="text/css" />    
 11     <script src="https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.js"></script>
 12 
 13     <!-- Jquery table JS引用 -->
 14     <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" type="text/css" />
 15     <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
 16 </head>
 17 
 18 <body>
 19 
 20 <h1><font color='red'>Jquery  DataTable testing</font></h1>
 21 <table id="example" class="display" style="width:100%">
 22         <thead>
 23             <tr>
 24                 <th>First name</th>
 25                 <th>Last name</th>
 26                 <th>Position</th>
 27                 <th>Office</th>
 28                 <th>Start date</th>
 29                 <th>Salary</th>
 30             </tr>
 31         </thead>
 32 </table>
 33 
 34 
 35 <hr/><hr/><br/><br/><br/>
 36 <h1><font color='red'>Jquery  DataTable testing2</font></h1>
 37 <table id="table2" class="display" style="width:100%">
 38         <thead>
 39             <tr>
 40                 <th> name</th>
 41                 <th>sex </th>
 42                 <th>age</th>
 43             </tr>
 44         </thead>
 45 </table>
 46 <hr/><hr/><br/><br/><br/>
 47 
 48 
 49 <h1><font color='red'>bootstrapTable  testing()跨域</font></h1>
 50 <table id="table3"></table>
 51 
 52 <hr/><hr/><br/><br/><br/>
 53 <input type="button" value="show table1" class="form-control" onclick="getvalue1()"/>
 54 <input type="button" value="show table2" class="form-control" onclick="getvalue2()"/>
 55 <input type="button" value="show table3" class="form-control" onclick="getvalue3()"/>
 56 
 57 <div id="employeeInfo" class="box-content">
 58 </div>
 59 
 60   <script type="text/javascript">
 61   
 62 function getvalue1()  {
 63     $('#example').DataTable( {
 64         ajax: {
 65             url: "http://localhost:8081/listUsers",
 66             dataType: "jsonp",
 67           "jsonp":"callback",
 68           "jsonpCallback":"success_jsonpCallback"
 69         }
 70     } );
 71 } 
 72 
 73 function getvalue2() { 
 74            $('#table2').DataTable( {
 75                 "processing": true,
 76                 "serverSide": true,
 77                 ajax: {
 78                     url: "http://localhost:8081/listUsers2",
 79                     dataType: "jsonp",
 80                   "jsonp":"callback",
 81                   "jsonpCallback":"success_jsonpCallback"
 82                     }
 83                 } );
 84 }
 85 
 86     
 87 function getvalue3() { 
 88         $.ajax({            
 89             "url": "http://localhost:8081/listUsers3",
 90             "dataType": "jsonp",
 91              "jsonp":"callback",
 92             "jsonpCallback":"success_jsonpCallback",
 93             "success":function(json,status){
 94                             console.log(json);
 95                                            for(var i = 0; i < json.rows.length; i++){
 96                                                 if(i == '0' && json.state == '3'){
 97                                                     json.rows[i].icon = 'end';
 98                                                 }else if(i == json.rows.length-1){
 99                                                     json.rows[i].icon = 'start';
100                                                 }else{
101                                                     json.rows[i].icon = 'step';
102                                                 }
103                                             };
104 
105                               console.log(status + "用户信息111:"+json.rows[1].id);
106                             switch(status){
107                                     case 'success':
108                                                creatbootstrapTable($('.table-progress'),json.rows);
109                                                break;
110                                        default :
111                                                alert('error');
112                                                break;
113                                 }
114                     }
115         });
116 }
117     
118 //调用bootstrapTable控件,数据用传入的json data.
119 function creatbootstrapTable($_obj, tableData){
120         var table = $('#table3').bootstrapTable({
121             //url: "http://localhost:8081/listUsers3",
122             data: tableData,
123             dataType: "json",
124             method: 'get',                      //请求方式(*)
125             //toolbar: '#toolbar',                //工具按钮用哪个容器
126             striped: true,                      //是否显示行间隔色
127             cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
128             pagination: true,                   //是否显示分页(*)
129             sortable: false,                     //是否启用排序
130             sortOrder: "asc",                   //排序方式
131             sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
132             pageNumber:1,                       //初始化加载第一页,默认第一页
133             pageSize: 8,                       //每页的记录行数(*)
134             pageList: [8,10, 25, 50, 100],        //可供选择的每页的行数(*)
135             search: false,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
136             strictSearch: true,
137             showColumns: false,                  //是否显示所有的列
138             showRefresh: true,                  //是否显示刷新按钮
139             minimumCountColumns: 2,             //最少允许的列数
140             clickToSelect: true,                //是否启用点击选中行
141             //height: 500,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
142             showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
143             cardView: false,                    //是否显示详细视图
144             detailView: false,                  //是否显示父子表
145             //得到查询的参数
146             queryParams : function (params) {
147                 return {
148                     pageSize: params.limit,
149                     pageNumber: params.offset/params.limit+1,
150                 };
151             },
152             columns: [{
153                 checkbox: true,  
154                 visible: true                  //是否显示复选框  
155             },{
156                 field: 'id',
157                 title: 'id'
158 
159             },{
160                 field: 'name',
161                 title: 'name'
162 
163             },{
164                 field: 'age',
165                 title: 'age'
166 
167             }],
168             onLoadSuccess: function (sta) {
169                     console.log("in onLoadSuccess");
170                     console.log(sta);
171             },
172             onLoadError: function (status, res) { //加载失败时执行
173                   alert("onLoadError");
174                   console.log(res);
175                   console.log(status);
176               }
177         });
178     }
179  </script>
180 </body>
181 </html>
View Code

2. NodeJS的入口程序service.js

 1 var express = require('express');
 2 var app = express();
 3 var fs = require("fs");
 4 
 5 //添加的新用户数据
 6 var user = {
 7    "user4" : {
 8       "name" : "mohit",
 9       "password" : "password4",
10       "profession" : "teacher",
11       "id": 4
12    }
13 }
14 
15 
16 
17 app.get('/listUsers', function (req, res) {
18    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
19        console.log( data );
20 
21        /**设置响应头允许ajax跨域访问**/
22 res.setHeader("Access-Control-Allow-Origin","*");
23 /*星号表示所有的异域请求都可以接受,*/
24 res.setHeader("Access-Control-Allow-Methods","GET,POST");
25 
26 
27       res.end( data );
28    });
29 })
30 
31 
32 app.get('/listUsers2', function (req, res) {
33    fs.readFile( __dirname + "/" + "users2.json", 'utf8', function (err, data) {
34        console.log( data );
35 
36        /**设置响应头允许ajax跨域访问**/
37 res.setHeader("Access-Control-Allow-Origin","*");
38 /*星号表示所有的异域请求都可以接受,*/
39 res.setHeader("Access-Control-Allow-Methods","GET,POST");
40 
41 
42       res.end( data );
43    });
44 })
45 
46 app.get('/listUsers3', function (req, res) {
47    fs.readFile( __dirname + "/" + "users3.json", 'utf8', function (err, data) {
48        console.log( data );
49 
50        /**设置响应头允许ajax跨域访问**/
51 res.setHeader("Access-Control-Allow-Origin","*");
52 /*星号表示所有的异域请求都可以接受,*/
53 res.setHeader("Access-Control-Allow-Methods","GET,POST");
54 
55 
56       res.end( data );
57    });
58 })
59 
60 
61 
62 app.get('/addUser', function (req, res) {
63    // 读取已存在的数据
64    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
65        data = JSON.parse( data );
66        data["user4"] = user["user4"];
67        console.log( data );
68        res.end( JSON.stringify(data));
69    });
70 })
71 
72 var server = app.listen(8081, function () {
73 
74   var host = server.address().address
75   var port = server.address().port
76   console.log("应用实例,访问地址为 http://%s:%s", host, port)
77 
78 })
View Code

3.NodeJS 的service.js调用的3个Json文件
3.1  users.json

 1 success_jsonpCallback(
 2 
 3 {
 4   "draw": 1,
 5   "recordsTotal": 57,
 6   "recordsFiltered": 57,
 7   "data": [
 8     [
 9       "Airi",
10       "Satou",
11       "Accountant",
12       "Tokyo",
13       "28th Nov 08",
14       "$162,700"
15     ],
16     [
17       "Cedric",
18       "Kelly",
19       "Senior Javascript Developer",
20       "Edinburgh",
21       "29th Mar 12",
22       "$433,060"
23     ]
24   ]
25 }
26 
27 )
View Code

3.2 users2.json

 1 success_jsonpCallback(
 2 
 3 {
 4   "draw": 1,
 5   "recordsTotal": 57,
 6   "recordsFiltered": 57,
 7   "data": [
 8     [
 9       "zhangsan",
10       "male",
11       "18"
12     ],
13     [
14       "lisi",
15       "female",
16       "25"
17     ]
18   ]
19 }
20 
21 )
users2.json

3.3

 1 success_jsonpCallback(
 2 
 3 {
 4     "total": 364,
 5     "rows": [{
 6         "id": "1",
 7         "name": "zhang san",
 8         "age": 30
 9 
10     }, {
11         "id": "2",
12         "name": "Li si",
13         "age": 25
14 
15     }]
16 }
17 
18 
19 
20 
21 )
users3.json

猜你喜欢

转载自www.cnblogs.com/ykxian01/p/9566060.html