Advertisements :

จะเขียนโปรแกรมที่เกี่ยวกับการใช้ php เป็นคล้ายๆ robots ไปดูด content จากเว็บอื่นๆมา analysis ทีนี้เลยต้องศึกษาเกี่ยวกับการใช้ Ajax ค่อยๆมาดูกันดีกว่า จากคนที่เขียน Ajax ไม่เป็นจะทำได้ไหม ฮ่าๆๆ

1. ผม search เพื่อหาเว็บโดยใช้ Keyword “Ajax chat tutorial” ใน Google ได้เป็นเว็บนี้มาครับ ajaxprojects.com

2. ผม Download ไฟล์ตัวอย่างมาติดตั้งในเครื่องผมเอง > Download source code - 7 Kb

3. ดูตามไปเรื่อยๆนะครับ อาจจะข้ามๆไปบ้าง เอาที่สำคัญๆนะ

The JavaScript

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('p_status').innerHTML 'Status: Cound not create XmlHttpRequest Object.' +
'Consider upgrading your browser.';
}
}

เค้าบอกว่า function นี้จะตรวจดูว่า Browser เป็นยี่ห้อใด แล้วใช้ Object ที่ใช้เชื่อม XMLHttpRequest ตัวไหนนั้นเอง จริงๆแล้วมี IE เจ้าเดียวแหละครับที่แปลกกว่าชาวบ้านเขา คือใช้ ActiveXObject(”Microsoft.XMLHTTP”)

var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;

สร้าง ตัวแปรเพื่อรับข้อความล่าสุดจากโปรแกรม, การรับค่าจะเป็น Plain Text ธรรมดาๆ หรือ XML ก็ได้ แต่ในที่นี้นี้จะรับค่ามาเป็น XML

//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}

function รับค่า text โดยส่งค่าไปเป็น lastmessage เพื่อเช็คดูว่าใน database มี update กว่านี้ไหม? ถ้ามีก็จะได้รับ chat text ใหม่ กลับมาก

Tags: , , , , , , ,

Page copy protected against web site content infringement by Copyscape

All product names are trademarks of their respective companies.Every effort is made to ensure content integrity. Use information on this site at your own risk. Information furnished in the blog is collected from various sites. This blog does not host any files on its server. Please report any broken links in comment. . Contact us at alongkorn.s(at)gmail.com