บทที่ 6 jquery, ajax และ javascript object notation (json) · jquery syntax : the...

50
วิชา เทคโนโลยีเว็บ (รหัสวิชา 04-06-204) jQuery, AJAX และ JavaScript Object Notation (JSON) บทที่ 6 เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 1

Upload: others

Post on 02-Apr-2020

33 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

วิชา เทคโนโลยีเว็บ (รหัสวิชา 04-06-204)

jQuery, AJAX และ JavaScript Object Notation (JSON) บทที่ 6

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

1

Page 2: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

วัตถุประสงค์การเรียนรู้

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

2

เพื่อให้ผู้เรียนมีความรู้ความเข้าใจเกี่ยวกับภาษา JavaScript library: jQuery, Asynchronous JavaScript and XML (AJAX) และ JavaScript Object Notation (JSON)

เพื่อให้ผู้เรียนประยุกต์ใช้งาน jQuery และ AJAX ที่สามารถประมวลผลและแสดงผลข้อมูลอย่างง่ายได ้

เพื่อให้ผู้เรียนมีความรู้เข้าใจเกี่ยวกับโครงสร้างการจัดเก็บข้อมูลแบบ JSON และสามารถพัฒนาโปรแกรมเพื่อเรียกใช้งานเอกสารดังกล่าวได้

Page 3: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

หัวข้อ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

3

บทน า (Overview)

JavaScript library: jQuery

Asynchronous JavaScript and XML (AJAX)

JavaScript Object Notation (JSON)

สรุป (Summary)

Page 4: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

บทน า (Overview)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

4

jQuery

• JavaScript library • Framework ส าหรับโปรแกรมประยุกต์บนเว็บ

AJAX • เป็นเทคนิคการพัฒนาเว็บแอปพลิเคชัน เพื่อให้สามารถโต้ตอบกับผู้ใช้ได้ดีขึ้น

JSON • เอกสารวัตถุจาวาสคริปต์ โดยไวยกรณ์เหมาะกับการจัดเก็บและแลกเปลี่ยนข้อมลู

Page 5: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JavaScript library: jQuery

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

5

JavaScript Framework Libraries

ที่มา: http://jquery.com/ และ http://jqueryui.com/demos/

<!DOCTYPE html> <html> <head> <title>jQuery</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js"></script> </head> <body> . . </body> </html>

Page 6: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery Syntax

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

6

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action() A $ sign to define/access jQuery

A (selector) to "query (or find)" HTML elements

A jQuery action() to be performed on the element(s)

Examples: $(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Page 7: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery Syntax : The Document Ready Event

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

7

$(document).ready(function(){

// jQuery methods go here...

});

$(function(){

// jQuery methods go here...

});

jQuery Selectors $("p") - The element Selector $("#test") - The #id Selector $(".test") - The .class Selector

$(document).ready(function(){

$("button").click(function(){

$(".test").hide();

});

});

Page 8: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 8

JavaScript:

function myFunction() {

var obj = document.getElementById("h01");

obj.innerHTML = "Hello jQuery";

}

onload = myFunction;

jQuery:

function myFunction() {

$("#h01").html("Hello jQuery");

}

$(document).ready(myFunction);

• passes the HTML DOM document object to jQuery: $(document) • myFunction can be passed as a variable to the jQuery ready()

method

Page 9: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery (ต่อ)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

9

DOM Traversal and Manipulation

$( "button.continue" ).html( "Next Step..." )

Event Handling

var hiddenBox = $( "#banner-message" );

$( "#button-container button" ).on( "click", function( event ) {

hiddenBox.show();

});

Ajax

$.ajax({

url: "/api/getWeather",

data: { zipcode: 97201 },

success: function( data ) {

$( "#weather-temp" ).html( "<strong>" + data + "</strong> degrees" );

}

});

Page 10: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery Event Methods

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

10

ที่มา: https://www.w3schools.com/jquery/jquery_events.asp

$("p").click(function(){

// action goes here!! });

$("p").click(function(){

$(this).hide();

});

$("input").focus(function(){

$(this).css("background-color", "#cccccc");

});

Page 11: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery (ต่อ)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

11

$( "form" ).submit(function( event ) { if ( $( "…(a)…" ).val() === "correct" ) { $( "span" ).text( "Validated..." ).show(); return; } $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 ); event.preventDefault(); });

Page 12: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Effect Basic

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

12

.effectBasic( [duration ] [, complete ] )

Hide $( "#target" ).hide("slow", function() {

//Code, Hide the matched elements.

});

Show $( "#target" ).show("slow", function() {

//Code, Display the matched elements.

});

Toggle $( "#target" ).toggle("slow", function() {

//Code, Display or hide the matched elements.

});

Page 13: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 13

... <script src="https://code.jquery.com/jquery-1.10.2.js"></script> ... <button id="hider">Hide</button> <button id="shower">Show</button> <div> <span>Once</span> <span>upon</span> <span>a</span> <span>time</span> <span>there</span> <span>were</span> <span>three</span> <span>programmers...</span> </div> <script> $( "#hider" ).click(function() { $( "span:last-child" ).hide( "fast", function() { // Use arguments.callee so we don't need a named function $( this ).prev().hide( "fast", arguments.callee ); }); }); $( "#shower" ).click(function() { $( "span" ).show( 2000 ); }); </script>

ที่มา: http://api.jquery.com/hide/

Page 14: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 14 ที่มา: http://api.jquery.com/toggle/

... <script src="https://code.jquery.com/jquery-1.10.2.js"></script> ... <button>Toggle 'em</button> <p>Hiya</p> <p>Such interesting text, eh?</p> <script> $( "button" ).click(function() { $( "p" ).toggle( "slow" ); }); </script>

Page 15: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Mouse Events

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

15

Click $( "#target" ).click(function() {

//Code

});

Toggle $( "#target" ).toggle(function() {

//Code

});

Double Click $( "#target" ).dblclick(function() {

//Code

});

Page 16: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 16 ที่มา: http://api.jquery.com/category/events/mouse-events/

... <script src="https://code.jquery.com/jquery-1.10.2.js"></script> ... <p>First Paragraph</p> <p>Second Paragraph</p> <p>Yet one more Paragraph</p> <script> $( "p" ).click(function() { $( this ).slideUp(); }); $( "p" ).dblclick(function() { alert( "Hello World!" ); }); </script> $( "td" ).toggle(

function() { $( this ).addClass( "selected" ); }, function() { $( this ).removeClass( "selected" ); } );

Page 17: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Form Events

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

17

Change $( "#target" ).change(function() {

// Code here

});

Focus $( "#target" ).focus(function() {

// Code here

});

Submit $( "#target" ).submit(function() {

// Code here

});

Page 18: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 18

ที่มา: http://api.jquery.com/category/events/form-events/ http://www.w3schools.com/jquery/jquery_ref_selectors.asp

... <script src="https://code.jquery.com/jquery-1.10.2.js"></script> ... <select name="sweets" multiple="multiple"> <option>Chocolate</option> <option selected="selected">Candy</option> <option>Taffy</option> <option selected="selected">Caramel</option> <option>Fudge</option> <option>Cookie</option> </select> <div></div> <script> $( "select" ).change(function () { var str = ""; $( "select option:selected" ).each(function() { str += $( this ).text() + " "; }); $( "div" ).text( str ); }).change(); </script>

$( "input[type='text']" ).change(function() { // Check input( $( this ).val() ) for validity here });

Page 19: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 19 ที่มา: http://api.jquery.com/category/events/form-events/

... <script src="https://code.jquery.com/jquery-1.10.2.js"></script> ... <p>Type 'correct' to validate.</p> <form action="javascript:alert( 'success!' );"> <div> <input type="text"> <input type="submit"> </div> </form> <span></span> <script> $( "form" ).submit(function( event ) { if ( $( "input:first" ).val() === "correct" ) { $( "span" ).text( "Validated..." ).show(); return; } $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 ); event.preventDefault(); }); </script>

Page 20: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

AJAX Overview

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

20

ที่มา: http://th.wikipedia.org/wiki/เอแจ็กซC์#mediaviewer/File:Ajax_model-th.png

Page 21: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery Ajax

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

21

ajax() method Used to perform an AJAX (asynchronous HTTP) request

$("#button").click(function(){ $.ajax({url:"demo_test.txt", success:function(result){ $("#div1").html(result); } }); });

$.ajax({name:value, name:value, ... })

ที่มา: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

Page 22: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery Ajax (ต่อ)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

22

ajaxComplete() method run when an AJAX request completes

ajaxStart() method run when an AJAX request starts

$(document).ajaxStart(function(){ //Code here }); $(document).ajaxComplete(function(){ //Code here });

Page 23: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 23

ที่มา: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

... <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).ajaxStart(function(){ $("#wait").css("display", "block"); }); $(document).ajaxComplete(function(){ $("#wait").css("display", "none"); }); $("button").click(function(){ $("#txt").load("demo_ajax_load.asp"); }); }); </script> ... <div id="txt"><h2>Let AJAX change this text</h2></div> <button>Change Content</button> <div id="wait" style="display:none;width:69px;height:89px;border:1px solid black;position:absolute;top:50%;left:50%;padding:2px;"><img src='demo_wait.gif' width="64" height="64" /><br>Loading..</div>

Page 24: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 24

ท่ีมา: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

... <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){ if(statusTxt == "success") alert("External content loaded successfully!"); if(statusTxt == "error") alert("Error: " + xhr.status + ": " + xhr.statusText); }); }); }); </script> ... <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> ...

Page 25: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

jQuery - AJAX get() and post() Methods

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

25

HTTP Request: GET vs. POST Two commonly used methods for a request-response between a client

and server are: GET and POST. GET - Requests data from a specified resource

POST - Submits data to be processed to a specified resource

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

Page 26: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 26

Syntax: $.get(URL,callback);

$("button").click(function(){ $.get("demo_test.php", function(data, status) { alert("Data: " + data + "\nStatus: " + status); }); });

Page 27: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 27

Syntax: $.post(URL,data,callback);

$("button").click(function(){ $.post("demo_test_post.php", { name: "Donald Duck", city: "Duckburg" }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); });

Page 28: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Example: demo_test.php or demo_test_post.php

<?php

//demo_test.php

echo “This is some text file from an external PHP file.”;

?>

<?php

//demo_test_post.php

echo “You post data about:<br/>”;

echo “Name = ”.$_POST[“name”].”<br/>”;

echo “City = ”.$_POST[“city”].”<br/>”;

?>

เอกสารประกอบการสอน

28

รายวิชา เทคโนโลยีเว็บ (04-06-204)

Page 29: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JavaScript Object Notation (JSON)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

29

JSON: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is an easier-to-use alternative to XML.

{ "employees":[

{"firstName":"John", "lastName":"Doe"},

{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter", "lastName":"Jones"}

] }

ที่มา: http://www.w3schools.com/js/js_json_intro.asp

Page 30: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

What is JSON?

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

30

JSON stands for JavaScript Object Notation

JSON is a lightweight data-interchange format

JSON is language independent *

JSON is "self-describing" and easy to understand

JSON - Evaluates to JavaScript Objects

Page 31: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 31

<!DOCTYPE html>

<html>

<body>

<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>

<script> var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; var obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone; </script>

</body>

</html>

Page 32: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Much Like XML Because

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

32

Both JSON and XML are "self describing" (human readable)

Both JSON and XML are hierarchical (values within values)

Both JSON and XML can be parsed and used by lots of programming languages

Both JSON and XML can be fetched with an XMLHttpRequest

Page 33: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Much Unlike XML Because

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

33

JSON doesn't use end tag

JSON is shorter

JSON is quicker to read and write

JSON can use arrays

Page 34: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

Why JSON?

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

34

For AJAX applications, JSON is faster and easier than XML:

Using XML Fetch an XML document

Use the XML DOM to loop through the document

Extract values and store in variables

Using JSON Fetch a JSON string

JSON.Parse the JSON string

Page 35: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON Syntax

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

35

JSON Syntax Rules

Data is in name/value pairs

Data is separated by commas

Curly braces hold objects

Square brackets hold arrays

The JSON syntax is a subset of the JavaScript syntax.

Page 36: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON Syntax (ต่อ)

JSON Data - A Name and a Value "firstName":"John" JSON Values A number (integer or floating

point) A string (in double quotes) A Boolean (true or false) An array (in square brackets) An object (in curly braces) null

เอกสารประกอบการสอน

36

รายวิชา เทคโนโลยีเว็บ (04-06-204)

{"firstName":"John", "lastName":"Doe"}

"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter","lastName":"Jones"} ]

Page 37: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON Uses JavaScript Syntax

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

37

var employees = [

{"firstName":"John", "lastName":"Doe"},

{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter","lastName": "Jones"}

];

With JavaScript you can create an array of objects and assign data to it, like this:

// returns John Doe employees[0].firstName + " " + employees[0].lastName; employees[0]["firstName"] + " " + employees[0]["lastName"];

employees[0].firstName = "Gilbert"; employees[0]["firstName"] = "Gilbert";

Page 38: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON Files

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

38

The file type for JSON files is ".json"

The MIME type for JSON text is "application/json"

Page 39: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON How To

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

39

Object From String Create a JavaScript string containing JSON syntax:

The JavaScript function JSON.parse(text) can be used to convert a JSON

text into a JavaScript object:

var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

var obj = JSON.parse(text);

Page 40: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 40

<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p id="demo"></p> <script> var text = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script> </body> </html>

Create Object from JSON String

Anna Smith

Web Browsers Support

• Firefox 3.5

• Internet Explorer 8

• Chrome

• Opera 10

• Safari 4

Page 41: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON Http Request

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

41

A common use of JSON is to read data from a web server, and display the data in a web page.

This chapter will teach you, in 4 easy steps, how to read JSON data, using XMLHttp. 1: Create an array of objects.

2: Create a JavaScript function to display the array.

3: Create a text file

4: Read the text file with an XMLHttpRequest

Page 42: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

1: Create an array of objects.

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

42

Use an array literal to declare an array of objects.

Give each object two properties: display and url.

Name the array myArray:

var myArray = [ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]

Page 43: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

2: Create a JavaScript function to display the array.

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

43

Create a function myFunction() that loops the array objects, and display the content as HTML links:

function myFunction(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>'; } document.getElementById("id01").innerHTML = out; }

myFunction(Array);

Page 44: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

3: Create a text file

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

44

Json Parser Online http://json.parser.online.fr/

[ { "display": "JavaScript Tutorial", "url": "http://www.w3schools.com/js/default.asp" }, { "display": "HTML Tutorial", "url": "http://www.w3schools.com/html/default.asp" }, { "display": "CSS Tutorial", "url": "http://www.w3schools.com/css/default.asp" } ]

myTutorials.txt

Page 45: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

4: Read the text file with an XMLHttpRequest

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

45

Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:

var xmlhttp = new XMLHttpRequest(); var url = "myTutorials.txt"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); myFunction(myArr); } }; xmlhttp.open("GET", url, true); xmlhttp.send();

Page 46: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

JSON SQL

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

46

This example reads JSON data from a web server running PHP and MySQL:

<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT CompanyName, City, Country FROM Customers"); $outp = "["; while($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "[") {$outp .= ",";} $outp .= '{"Name":"' . $rs["CompanyName"] . '",'; $outp .= '"City":"' . $rs["City"] . '",'; $outp .= '"Country":"'. $rs["Country"] . '"}'; } $outp .="]"; $conn->close(); echo($outp); ?>

Page 47: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204) 47

<div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = "http://www.w3schools.com/website/customers_mysql.php"; xmlhttp.onreadystatechange=function() { if (this.readyState == 4 && this.status == 200) { myFunction(this.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; for(i = 0; i < arr.length; i++) { out += "<tr><td>" + arr[i].Name + "</td><td>" + arr[i].City + "</td><td>" + arr[i].Country + "</td></tr>"; } out += "</table>"; document.getElementById("id01").innerHTML = out; } </script>

ที่มา: http://www.w3schools.com/js/js_json_sql.asp

Page 48: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

สรุป (Summary)

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

48

ศึกษาและเรียนรู้เกี่ยวกับ โครงสร้างและไวยากรณ์ JavaScript Library: jQuery และการใช้

งานเบื้องต้น

โครงสร้างและไวยากรณ์เอกสาร JSON และการใช้งานเบื้องต้น

AJAX ที่ซึ่งใช้งาน jQuery Ajax และประยุกต์ใช้งานกับเอกสาร JSON และ Server Side Script เบื้องต้น

Page 49: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

แบบฝึกปฏิบัต ิ

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

49

ก าหนดให้พัฒนาโปรแกรมโดยใช้ XMLHttpRequest เพื่ออ่านข้อมูล JSON SQL ดังนี้

ก าหนดแหล่งข้อมูล JSON SQL [URL JSON Document]

การแสดงผลข้อมูลดังกล่าว สามารถเรียกใช้แท็ก <table>, <p>, <div>, <ul> หรืออื่น ๆ ตามความเหมาะสม

ประยุกต์ใช้ jQuery Effect Basic ส าหรับการแสดงผล และตรวจสอบผลการด าเนินการ

Page 50: บทที่ 6 jQuery, AJAX และ JavaScript Object Notation (JSON) · jQuery Syntax : The Document Ready Event รายวิชา เทคโนโลยีเว็บ

เอกสารอ้างอิง

เอกสารประกอบการสอน รายวิชา เทคโนโลยีเว็บ (04-06-204)

50

jQuery (Online), Available at: http://jquery.com/

AJAX Introduction (Online), Available at: http://www.w3schools.com/ajax/ajax_intro.asp

JSON Introduction (Online), Available at: http://www.w3schools.com/js/js_json_intro.asp

Paul Wilton and Jeremy McPeak, Beginning JavaScript® Fourth Edition, Wiley Publishing, Inc., 2010.