Wednesday, February 19, 2014

Ajax - Client and Server side processing.

<!DOCTYPE html>
<html>
<head>
<title>Test for Ajax</title>
<link href="http://fonts.googleapis.com/css?family=Abel" rel="stylesheet" type="text/css">
<link href="http://monologue-js.herokuapp.com/style.css" rel="stylesheet" type="text/css">
<script src="/htmlTest/js/jquery-1.9.1.js"></script>
<script src="/htmlTest/js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#new-status form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/admin/real/test.sg',
contentType: "application/json",
dataType: "json",
data: "{ 'text' : '" + $('#new-status').find('textarea').val() + "'}",
success: function(data, textStatus, jqXHR) {
// {"aaa":"ddd"}, Don't do this like that {'aaa':'ddd'}
alert(">>>" + data.aaa); // >>>ddd
$('#statuses').append('<li>' + data.aaa + '</li>');
$('#new-status').find('textarea').val('');
},
error: function(xhr, status) {
//alert(xhr.responseText);
}
});
});
});
</script>
</head>
<body>
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea></textarea><br>
<input type="submit" value="Post"/>
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
</body>
</html>
view raw AjaxClient hosted with ❤ by GitHub
package jp.test.controller;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/real")
public class TestController extends AbstractBaseController {
@RequestMapping(value = {"test.sg"})
public void test(@RequestBody String body, HttpServletResponse response) throws Exception {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter pw = response.getWriter();
pw.write("{\"aaa\":\"ddd\"}");
pw.flush();
pw.close();
}
}
view raw AjaxServer hosted with ❤ by GitHub

No comments:

Post a Comment