/
json.gtw
79 lines (57 loc) · 1.81 KB
/
json.gtw
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
~~LANG:FR@frman:modules/services-web/json~~
[[https://en.wikipedia.org/wiki/JSON|JSON]] is a data format using javascript
syntax. This ease greatly the use of JSON encoded data in HTML content.
To send JSON data, there is a specific @@C@jResponseJson@@ object. Its alias is
"json". All you need to do is to assign your encoded json to the @@P@$data@@
property:
<code php>
$resp = $this->getResponse('json');
$resp->data = array( 'lastname'=>'dupont', 'firstname'=>'jean');
return $resp;
</code>
To call the action, in raw javascript :
<code javascript>
var http = new XMLHttpRequest();
//url is a variable which contains the url of the action
http.open("post", url, true);
http.onreadystatechange = function(){
if(http.readyState == 4){
// Get the data from the server's response
var json = http.responseText;
var value = JSON.parse(json);
// do something with your json data
}
};
http.send(null);
</code>
or, with jQuery:
<code javascript>
$.getJSON( url, function (json) {
// do something with your json data
}
</code>
With our example, the client will receive:
<code javascript>
{ "lastname":"dupont", "firstname":"jean"}
</code>
And then the whole client process with jQuery is :
<code javascript>
$.getJSON( url, function (json) {
alert(json.lastname + ' ' + json.firstname);
});
</code>
=== A use case combined with jDao ===
In your controller:
<code php>
$countryDao = jDao::get('common~country');
$countries = $countryDao->findAll();
$response = $this->getResponse('json');
$response->data = array();
foreach($countries as $country) {
$response->datas[] = array('id' => $country->id , 'name' => $country->name);
}
</code>
The client will receive:
<code javascript>
{ "id":20, "name":"Europe"}
</code>