웹개발/HTML

Ajax2

에르소 2014. 5. 23. 17:28
반응형



 Ajax Part2


DOM (Document Object Model)




UsingDom.html

changeUsingDom.html



[서버에서 XML 응답 생성하기]

[books.jsp]

<?xml version="1.0" encoding="euc-kr" ?>

<%@ page contentType="text/xml; charset=euc-kr" %>


<books>

    <book>

        <title>프로젝트 생존 전략</title>

        <author>스티브 맥코넬</author>

    </book>

    <book>

        <title>JSP 2.0 프로그래밍</title>

        <author>최범균</author>

    </book>

    <book>

        <title>웹 표준</title>

        <author>댄 씨더홈</author>

    </book>

</books>


<book> 은 3개 / <books> 메인 엘리먼트

<web-app> root엘리먼트

앨리먼트 (xml) / 태그 (html)

xmls = xsd (xml schema) 이파일안에 정의되어있다.



[viewBooks.html]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">

<head>

<meta http-equiv="content-type" content="text/html; charset=euc-kr" />

<title>책정보 보기</title>

<script type="text/javascript" src="httpRequest.js"></script>

<script type="text/javascript">

function loadBooks() {

sendRequest("books.jsp", null, loadedBooks, "GET");

}

function loadedBooks() {

if (httpRequest.readyState == 4) {

if (httpRequest.status == 200) {

var xmlDoc = httpRequest.responseXML;

var bookList = xmlDoc.getElementsByTagName("book");

var message = "책 개수 : "+bookList.length+"권\n";

for (var i = 0 ; i < bookList.length ; i++) {

var book = bookList.item(i);

var titleValue = book.getElementsByTagName("title").item(0)

                    .firstChild.nodeValue;

var authorValue = book.getElementsByTagName("author").item(0)

                     .firstChild.nodeValue;

message += titleValue + "(" + authorValue + ")\n";

}

alert(message);

}

}

}

window.onload = function() {

loadBooks();

}

</script>

</head>

<body>

책 정보를 alert 으로 출력

</body>

</html>



[ JSON 표기법 ]


[ajax.js : 클래스로 XMLHttpRequest 모듈 만들기]

var ajax = {};

ajax.xhr = {};


ajax.xhr.Request = function(url, params, callback, method) {

this.url = url;

this.params = params;

this.callback = callback;

this.method = method;

this.send();

}

ajax.xhr.Request.prototype = {

getXMLHttpRequest: function() {

if (window.ActiveXObject) {

try {

return new ActiveXObject("Msxml2.XMLHTTP");

} catch(e) {

try {

return new ActiveXObject("Microsoft.XMLHTTP");

} catch(e1) { return null; }

}

} else if (window.XMLHttpRequest) {

return new XMLHttpRequest();

} else {

return null;

}

},

send: function() {

this.req = this.getXMLHttpRequest();

var httpMethod = this.method ? this.method : 'GET';

if (httpMethod != 'GET' && httpMethod != 'POST') {

httpMethod = 'GET';

}

var httpParams = (this.params == null || this.params == '') ? 

                null : this.params;

var httpUrl = this.url;

if (httpMethod == 'GET' && httpParams != null) {

httpUrl = httpUrl + "?" + httpParams;

}

this.req.open(httpMethod, httpUrl, true);

this.req.setRequestHeader(

'Content-Type', 'application/x-www-form-urlencoded');

var request = this;

this.req.onreadystatechange = function() {

request.onStateChange.call(request);

}

this.req.send(httpMethod == 'POST' ? httpParams : null);

},

onStateChange: function() {

this.callback(this.req);

}

}



[loadMemberFromXML.html]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">

<head>

<meta http-equiv="content-type" content="text/html; charset=euc-kr" />

<title>XML로부터 객체 생성</title>

<script type="text/javascript" src="ajax.js"></script>

<script type="text/javascript" src="member.js"></script>

<script type="text/javascript">

window.onload = function() {

new ajax.xhr.Request("member_xml.jsp", "", viewInfo, "GET");

}

function viewInfo(req) {

if (req.readyState == 4) {

if (req.status == 200) {

var docXML = req.responseXML;

var code = docXML.getElementsByTagName("code")

                .item(0).firstChild.nodeValue;

if (code == 'success') {

var name = docXML.getElementsByTagName("name")

                .item(0).firstChild.nodeValue;

var id = docXML.getElementsByTagName("id")

                .item(0).firstChild.nodeValue;

var sno = docXML.getElementsByTagName("sno")

                .item(0).firstChild.nodeValue;


var mem = new Member(name, id, sno);

alert(mem.toString() + ", " + mem.getAge() +"세");

} else {

alert("실패");

}

} else {

alert("에러 발생:"+req.status);

}

}

}

</script>

</head>

<body>

</body>

</html>



[member_json.jsp]

<%@ page contentType="text/plain; charset=euc-kr" %>

{

code: 'success',

data: {

member: {

name: '최범균',

id: 'madvirus',

sno: '7700001000000'

}

}

}



[loadMemberFromJSON.html]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">

<head>

<meta http-equiv="content-type" content="text/html; charset=euc-kr" />

<title>JSON으로부터 객체 생성</title>

<script type="text/javascript" src="ajax.js"></script>

<script type="text/javascript">

window.onload = function() {

new ajax.xhr.Request("member_json.jsp", "", viewInfo, "GET");

}

function viewInfo(req) {

if (req.readyState == 4) {

if (req.status == 200) {

var result = eval("(" + req.responseText + ")");

if (result.code == 'success') {

var m = result.data.member;

alert(m.id + "[" + m.name + "]");

} else {

alert("실패");

}

} else {

alert("에러 발생:"+req.status);

}

}

}

</script>

</head>

<body>

</body>

</html>




XML  JSON 응답을 객체로 변환 

[member_xmljson.jsp]

<?xml version="1.0" encoding="euc-kr" ?>

<%@ page contentType="text/xml; charset=euc-kr" %>


<result>

<code>success</code>

<data><![CDATA[

{

name: '최범균',

id: 'madvirus',

sno: '7700001000000'

}

]]>

</data>

</result>



[Util.java]

package util;


public class Util {

public static String toJS(String str) {

return str.replace("\\", "\\\\")

         .replace("\'", "\\\'")

         .replace("\"", "\\\"")

         .replace("\r\n", "\\n")

         .replace("\n", "\\n");

}

}



P.475



반응형

'웹개발 > HTML' 카테고리의 다른 글

톰캣 에러  (0) 2014.05.28
Ajax3  (0) 2014.05.26
Ajax1  (0) 2014.05.22
툴팁 제작하기  (0) 2014.05.22
ALTER TABLE 문  (0) 2014.05.21