ป้ายกำกับ: เจเควียรี

jQuery Ajax แบบอนุกรมตามลำดับjQuery Ajax แบบอนุกรมตามลำดับ

งานที่ทำอยู่ต้องใช้เจคิวรี่เอแจ็คไปเรียกใช้สร้างตารางในฐานข้อมูลใหม่ แต่ถ้าใช้ ajax หลาย ๆ ชุดต่อ ๆ กันแทนที่มันจะทำงานตามลำดับแบบอนุกรม มันดันไปทำงานแบบขนานแทน บางตารางที่ต้องสร้างหลังเพราะกำหนดความสัมพันธ์ไว้กับตารางหลัก แต่ตารางหลักยังสร้างไม่เสร็จ ผลคือ การสร้างตารางทำไม่สำเร็จ

แก้ได้โดยบังคับให้ รอฟังก์ชั่นเดิมเสร็จก่อนแล้วจึงทำงานอื่น ๆ ต่อไป

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Ajax Synchronous By Pitt Phunsanit</title>
</head>
<body>
<div id="logs"></div>
<script src="../jQuery/jquery-2.1.3.min.js"></script>
<script>
$ (function () {

	logs = $ ('#logs') ;

	/* task order */
	var tasks = new Array () ;
	tasks.push ('one') ;
	tasks.push ('two') ;
	tasks.push ('three') ;



	/* process each step */
	function step (tasks, a) {
		$.ajax ({
			"cache" : false,
			"data" : 'task='+tasks[a],
			"dataTyp" : "html",
			"method" : "post",
			"success" : function (datas) {

				logs.append (datas) ;

				/* call next step */
				a++;
				if (typeof tasks[a] != 'undefined') {
					step (tasks, a) ;
				}

			},
			"url" : 'task.php'
		}) ;
	}

	/* call first time */
	step (tasks, 0) ;
}) ;
</script>
</body>
</html>
<?php
switch ($_POST['task']) {
	case 'one' :
	{
		echo '<h1>One</h1>';
	}break;
	case 'two' :
	{
		echo '<h1>Two</h1>';
	}break;
	case 'three' :
	{
		echo '<h1>three</h1>';
	}break;
}

ทีนี้มันจะทำงานตามลำดับ 1,2,3… อย่างถูกต้อง

ถ้าต้องการหยุดการทำงาน เช่น มี error ให้เปลี่ยนค่า a เป็นค่าที่ไม่มีอยู่จริง เช่น 9999 (คงไม่มี process กลุ่มไหนถึง) คำสั่ง typeof tasks[a] จะ return ‘undefined’ code ก็จะหยุดการทำงาน

อ่านเพิ่มเติม jQuery: Ajax รับข้อมูลแบบ stream