-
Notifications
You must be signed in to change notification settings - Fork 3
/
jsonp.html
113 lines (107 loc) · 2.75 KB
/
jsonp.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!-- DOM和浏览器中的模式:远程脚本编程——JSONP -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONP</title>
<style media="screen">
td {
width: 50px;
height: 50px;
font-size: 50px;
font-family: monospace;
border: 1px solid lightGrey;
text-align: center;
color: red;
}
.server {
color: blue;
}
body {
font-family: Helvetica;
}
</style>
</head>
<body>
<h1>Tic-tac-toe: <br>server "X" vs. client "O"</h1>
<button id="new">New game</button>
<button id="server">Server play</button>
<table>
<tr>
<td id="cell-1"> </td>
<td id="cell-2"> </td>
<td id="cell-3"> </td>
</tr>
<tr>
<td id="cell-4"> </td>
<td id="cell-5"> </td>
<td id="cell-6"> </td>
</tr>
<tr>
<td id="cell-7"> </td>
<td id="cell-8"> </td>
<td id="cell-9"> </td>
</tr>
</table>
<script>
var ttt = {
// cells played so far
played: [],
// shorthand
get: function(id) {
return document.getElementById(id);
},
// handle clicks
setup: function() {
this.get('new').onclick = this.newGame;
this.get('server').onclick = this.remoteRequest;
},
// clean the board
newGame: function() {
var tds = document.getElementsByTagName("td"),
max = tds.length,
i;
for (i = 0; i < max; i += 1) {
tds[i].innerHTML = " ";
}
ttt.played = [];
},
// make a request
remoteRequest: function() {
var script = document.createElement("script");
script.src = "server.php?callback=ttt.serverPlay&played=" + ttt.played.join(',');
document.body.appendChild(script);
},
// callback, server's turn to play
serverPlay: function(data) {
if (data.error) {
alert(data.error);
return;
}
data = parseInt(data, 10);
this.played.push(data);
this.get('cell-' + data).innerHTML = '<span class="server">X<\/span>';
setTimeout(function() {
ttt.clientPlay();
}, 300); // as if thinking hard
},
// client's turn to play
clientPlay: function() {
var data = 5;
if (this.played.length === 9) {
alert("Game over");
return;
}
// keep coming up with random numbers 1-9
// until one not taken cell is found
while (this.get('cell-' + data).innerHTML !== " ") {
data = Math.ceil(Math.random() * 9);
}
this.get('cell-' + data).innerHTML = 'O';
this.played.push(data);
}
};
ttt.setup();
</script>
</body>
</html>