Runoob Tutorial ArchiveEnglish

AJAX JSON instance

AJAX JSON instance


AJAX can be used to interactively communicate with JSON files.


AJAX JSON instance

The following example demonstrates how a webpage uses AJAX to read information from a JSON file:

Example

Try it »


Example parsing - loadXMLDoc() function

When the user clicks the **"Get Course Data"** button above, the loadXMLDoc() function is executed.

The loadXMLDoc() function creates an XMLHttpRequest object, adds a function to execute when the server response is ready, and sends the request to the server.

When the server response is ready, we use the JSON.parse() method to convert the data into a JavaScript object.

Asynchronous loading of JSON document

function

loadXMLDoc

(

)

{

var

xmlhttp

;

if

(

window

.

XMLHttpRequest

)

{

//

IE7+, Firefox, Chrome, Opera, Safari browser executes code

xmlhttp

=

new

XMLHttpRequest

(

)

;

}

else

{

//

Code execution for IE6, IE5 browsers

xmlhttp

=

new

ActiveXObject

(

"

Microsoft.XMLHTTP

"

)

;

}

xmlhttp

.

onreadystatechange

=

function

(

)

{

if

(

xmlhttp

.

readyState

==

4

&&

xmlhttp

.

status

==

200

)

{

var

myArr

=

JSON

.

parse

(

this

.

responseText

)

;

myFunction

(

myArr

)

}

}

xmlhttp

.

open

(

"

GET

"

,

"

/try/ajax/json_ajax.json

"

,

true

)

;

xmlhttp

.

setRequestHeader

(

"

Content-Type

"

,

"

application/json;charset=UTF-8

"

)

;

xmlhttp

.

send

(

)

;

}

function

myFunction

(

arr

)

{

var

out

=

"

"

;

var

i

;

for

(

i

=

0

;

i

<

arr

.

length

;

i

++

)

{

out

+=

'

<a href="

'

arr

[

i

]

.

url

'

">

'

arr

[

i

]

.

title

'


'

;

}

document

.

getElementById

(

"

myDiv

"

)

.

innerHTML

=

out

;

}


AJAX server page

The server page used in the example above is actually a JSON file named "json_ajax.json".

The JSON data is as follows:

json_ajax.json file:

[

{

"

title

"

:

"

JavaScript Tutorial

"

,

"

url

"

:

"

https://www.runoob.com/js/

"

}

,

{

"

title

"

:

"

HTML Tutorial

"

,

"

url

"

:

"

https://www.runoob.com/html/

"

}

,

{

"

title

"

:

"

CSS Tutorial

"

,

"

url

"

:

"

https://www.runoob.com/css/

"

}

]

Send JSON data:



xmlhttp.send(JSON.stringify({ "email": "admin@runoob.com", "response": { "name": "runoob" } }));