먼저 XHR 객체가 필요합니다. 이것은 우리에게는 어렵지 않습니다. 함수에 캡슐화합니다.
var createajax = function () {var xhr = null; try {// IE 시리즈 브라우저 XHR = New ActiveXobject ( "microsoft.xmlhttp"); } catch (e1) {try {// nonie 브라우저 xhr = new xmlhttprequest (); } catch (e2) {window.alert ( "브라우저는 Ajax를 지원하지 않습니다. 교체하십시오!"); }} return xhr;};그런 다음 핵심 기능을 작성해 봅시다.
var ajax = function (conf) {// 초기화 // 유형 매개 변수, 선택적 var type = conf.type; // URL 매개 변수, 필수 var url = conf.url; // 데이터 매개 변수는 선택 사항이며 var data = conf.data 만; // Datatype 매개 변수는 선택적 var datatype = conf.datatype입니다. // 콜백 함수는 선택적 var success = conf.success입니다. if (type == null) {// 유형 매개 변수는 선택 사항입니다. 기본값은 get type = "get"입니다. } if (dataType == null) {// DataType 매개 변수는 선택 사항입니다. 기본값은 텍스트 DataType = "Text"; } // ajax 엔진 개체 생성 var xhr = createajax (); // xhr.open을 엽니 다 (type, url, true); // if (type == "get"|| type == "get") {xhr.send (null); } else if (type == "post"|| type == "post") {xhr.setRequestheader ( "content-type", "application/x-www-form-urlencoded"); xhr.send (데이터); } xhr.onreadyStateChange = function () {if (xhr.readystate == 4 && xhr.status == 200) {if (dataType == "text"|| DataType == "text") {if (success! = null) {// 일반 텍스트 성공 (xhr.responsetext); }} else if (dataType == "XML"|| DataType == "XML") {if (success! = null) {// XML 문서 성공 (xhr.responsexml); }} else if (datatype == "json"|| datatype == "json") {if (success! = null) {// json 문자열 변환 객체 성공 ( "("+xhr.responsetext+")); }}}}}}};};마지막 으로이 기능의 사용법을 설명해 봅시다.
ajax ({type : "post", url : "test.jsp", data : "name = dipoo & info = good", dataType : "json", success : function (data) {alert (data.name);}});기본 J를 사용하여 Ajax를 간단히 캡슐화하는 위의 예제 코드는 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.