歡迎您光臨本站 註冊首頁

ajax入門小程序

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

此小程序主要給ajax還未入門的朋友們一個簡單的演示.程序的主要內容就是將頁面部分的id通過表單傳到java的servlet中,因為只是做示例,沒有對id進行任何處理,有興趣的朋友可以連接資料庫或應用一些jdk方法進行處理操作等等,在此僅作示例.話不多說了(這話就不少了),看代碼吧:

1、ajaxdemo.jsp

<%@ page language="java" pageEncoding="GB18030"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'ajaxdemo.jsp' starting page</title>
<script type="text/javascript">
var req;
function createAJAX() {
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}

function testAjax() {
var url = "/testajax/servlet/TestAjaxServlet?id=123";
createAJAX();
req.open("POST", url, true);
req.onreadystatechange = callback;
req.send(null);
}

function callback() {
if(req.readyState == 4) {
if(req.status == 200) {
document.getElementById("ajaxDiv").innerHTML = req.responseText;
}
}
}
</script>
</head>
<body>
<input type="button" value="測試ajax" name="button1" id="ajaxButton" onclick="testAjax()"><br>
可以根據下邊這個id號進行操作:<div id="ajaxDiv"></div>
</body>
</html>

說明:因為只是一個簡簡單單的玩意,頁面部分未使用任何ajax框架,只是用最基本的ajax原理實現.頁面會將id通過ajax傳到後台.

2、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>TestAjaxServlet</servlet-name>
<servlet-class>com.ajax.TestAjaxServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestAjaxServlet</servlet-name>
<url-pattern>/servlet/TestAjaxServlet</url-pattern>
</servlet-mapping>


<welcome-file-list>
<welcome-file>ajaxdemo.jsp</welcome-file>
</welcome-file-list>
</web-app>

說明:既然用到servlet了,那難免要配置一下web.xml了,將對應servlet信息配置在web.xml中.

3、TestAjaxServlet.java

package com.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class TestAjaxServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
String id = request.getParameter("id");
//可在此處判斷id是否為空,並根據id做你相應的處理,隨意!
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(id);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

}

說明,寫一個最最……簡單的doPost方法,可以加上你自己的代碼,處理完了id,把它毫不留情的扔回頁面,然後看看結果吧.

結尾:謹獻給接觸java web希望了解ajax但又在迷茫中的朋友.


[火星人 ] ajax入門小程序已經有711次圍觀

http://coctec.com/docs/java/show-post-62157.html