การใช้งาน xml ไฟล์ด้วย ajax ใน jQuery สามารถทำได้ง่าย ใช้ได้ทั้ง ฟังก์ชัน $.ajax() $.get()
และ $.post()
โดยส่วนใหญ่การใช้งาน xml ไฟล์ จะเป็นได้
ทั้งการดึงข้อมูลทั้งหมดมาแสดง
การดึงข้อมูลบางส่วน มาแสดงแบบมีเงื่อนไข
การดึงค่า attribute มาแสดง
ตัวอย่างไฟล์ simple_2.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <? xml version = "1.0" encoding = "utf-8" ?> < markers > < marker id = "1" > < name >กรุงเทพมหานคร</ name > < latitude >13.7234186</ latitude > < longitude >100.4762319</ longitude > </ marker > < marker id = "2" > < name >กระบี่</ name > < latitude >8.1191811</ latitude > < longitude >99.1013498</ longitude > </ marker > < marker id = "3" > < name >กาญจนบุรี</ name > < latitude >14.6701192</ latitude > < longitude >99.0128926</ longitude > </ marker > </ markers > |
ตัวอย่างโค้ด กรณีการดึงข้อมูลใน simple_2.xml ทั้งหมด มาแสดง
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | <button id= "act1" >Load XML Data From file simple_2.xml </button> <div id= "showXML" ></div> <script type= "text/javascript" src= "js/jquery-1.4.2.min.js" ></script> <script type= "text/javascript" > $( function (){ $( "#act1" ).click( function (){ // การ load xml ไฟล์ ด้วย ajax ใน jQuery ด้วย $.get() // $.get("simple_2.xml",function(xml){ // var dataResult=''; // $(xml).find("marker").each(function(){ // dataResult+=$(this).attr("id")+"<br>"; // การดึงค่า attribute ชือ id // dataResult+=$(this).find("name").text()+"<br>"; // dataResult+=$(this).find("latitude").text()+"<br>"; // dataResult+=$(this).find("longitude").text()+"<hr>"; // }); // $("#showXML").html(dataResult); // }); // การ load xml ไฟล์ ด้วย ajax ใน jQuery ด้วย $.post() // $.post("simple_2.xml",function(xml){ // var dataResult=''; // $(xml).find("marker").each(function(){ // dataResult+=$(this).attr("id")+"<br>"; // การดึงค่า attribute ชือ id // dataResult+=$(this).find("name").text()+"<br>"; // dataResult+=$(this).find("latitude").text()+"<br>"; // dataResult+=$(this).find("longitude").text()+"<hr>"; // }); // $("#showXML").html(dataResult); // }); // การ load xml ไฟล์ ด้วย ajax ใน jQuery ด้วย $.ajax() $.ajax({ url: "simple_2.xml" , dataType: "xml" , cache:false, // กำหนดให้ cache ข้อมูลที่โหลดมา หรือไม่ async:false, success: function (xml){ var dataResult= '' ; $(xml).find( "marker" ).each( function (){ dataResult+=$(this).attr( "id" )+ "<br>" ; // การดึงค่า attribute ชือ id dataResult+=$(this).find( "name" ).text()+ "<br>" ; dataResult+=$(this).find( "latitude" ).text()+ "<br>" ; dataResult+=$(this).find( "longitude" ).text()+ "<hr>" ; }); // dataResult=$(xml).find("marker:eq(0)").find("name").text(); // การดึงเฉพาะค่า หรือค่าเดียว $( "#showXML" ).html(dataResult); } }); }); // jQuery code }); </script> |