基于struts2,有2種標(biāo)準(zhǔn)方法實(shí)現(xiàn)ajax
共同的一點(diǎn)是,Action都需要將一個方法暴露出來,給前端javascript調(diào)用
javascript的代碼都是一樣的:
- function testAjax() {
-
- var $userNameInput = $("#ajax_username");
- var userName = $userNameInput.val();
-
- $.ajax({
- url : "originAjax.action",
- type : "GET",
- data : "ajaxField=" + userName,
- success : function(data, textStatus) {
- alert(data);
- }
- });
- }
這里originAjax.action,就是暴露出來供調(diào)用的地址
下面分別介紹服務(wù)端的兩種寫法
第一種是原生的寫法,不需要依賴插件,也沒有自行解析和拼裝json串的功能
Action:
- public void originAjax() throws IOException {
- HttpServletResponse response = ServletActionContext.getResponse();
- PrintWriter writer = response.getWriter();
- writer.print("hello " + ajaxField);
- writer.flush();
- writer.close();
- }
|