ก่อนอื่นเราต้องการวัตถุ XHR นี่ไม่ใช่เรื่องยากสำหรับเราห่อหุ้มมันลงในฟังก์ชั่น
var createAjax = function () {var xhr = null; ลอง {// ie series เบราว์เซอร์ xhr = new ActiveXObject ("microsoft.xmlhttp"); } catch (e1) {ลอง {// non-ie เบราว์เซอร์ xhr = ใหม่ xmlhttprequest (); } catch (e2) {window.alert ("เบราว์เซอร์ของคุณไม่รองรับ ajax โปรดแทนที่!"); }} ส่งคืน xhr;};จากนั้นเรามาเขียนฟังก์ชั่นหลักกันเถอะ
var ajax = function (conf) {// เริ่มต้นพารามิเตอร์ // ประเภทพารามิเตอร์, var type ตัวเลือก = conf.type; // พารามิเตอร์ URL, ต้องใช้ var url = conf.url; // พารามิเตอร์ข้อมูลเป็นทางเลือกเฉพาะ var data = conf.data; // พารามิเตอร์ข้อมูลเป็นตัวเลือก var datatype = conf.datatype; // ฟังก์ชั่นการโทรกลับเป็นตัวเลือก var success = conf.success; ถ้า (type == null) {// พารามิเตอร์ประเภทเป็นตัวเลือก, ค่าเริ่มต้นคือ get = "get"; } if (dataType == null) {// พารามิเตอร์ datatype เป็นตัวเลือก, ค่าเริ่มต้นคือ text datatype = "text"; } // สร้างวัตถุเครื่องยนต์ AJAX var xhr = createAjax (); // เปิด xhr.open (ประเภท, url, true); // ส่ง if (type == "get" || type == "get") {xhr.send (null); } อื่นถ้า (type == "post" || type == "post") {xhr.setRequestheader ("ประเภทเนื้อหา", "แอปพลิเคชัน/x-www-form-urlencoded"); XHR.Send (ข้อมูล); } xhr.onreadyStateChange = function () {ถ้า (xhr.readystate == 4 && xhr.status == 200) {ถ้า (datatype == "text" || datatype == "text") {ถ้า (ประสบความสำเร็จ! }} อื่นถ้า (dataType == "xml" || dataType == "xml") {ถ้า (ประสบความสำเร็จ! = null) {// รับความสำเร็จของเอกสาร XML (XHR.Responsexml); }} อื่นถ้า (dataType == "json" || datatype == "json") {ถ้า (ประสบความสำเร็จ! = null) {// แปลงสตริง JSON เป็น JS Object Success ("("+Xhr.ResponSetext+")))); -สุดท้ายเรามาอธิบายการใช้งานฟังก์ชั่นนี้
ajax ({type: "post", url: "test.jsp", data: "name = dipoo & info = good", ประเภทข้อมูล: "json", ความสำเร็จ: ฟังก์ชั่น (ข้อมูล) {alert (data.name);}});รหัสตัวอย่างข้างต้นที่ใช้ JS ดั้งเดิมเพื่อห่อหุ้ม AJAX เป็นเนื้อหาทั้งหมดที่ฉันแบ่งปันกับคุณ ฉันหวังว่าคุณจะให้ข้อมูลอ้างอิงและฉันหวังว่าคุณจะสนับสนุน wulin.com มากขึ้น