Ajax and JSON

Source: Internet
Author: User

AJAX is a technique to update parts of a Web page without reloading the entire page. AJAX = asynchronous JavaScript and XML. AJAX is a technique for creating fast, Dynamic Web pages.

AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.

XMLHttpRequest is the basis of AJAX. all modern browsers support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject). XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without reloading the entire page.

Create XMLHttpRequest The syntax of the object:

Variable=new XMLHttpRequest ();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
Variable=new ActiveXObject ("Microsoft.XMLHTTP");

var xmlhttp;
if (window. XMLHttpRequest)
{//code for ie7+, Firefox, Chrome, Opera, Safari
Xmlhttp=new XMLHttpRequest ();
}
Else
{//code for IE6, IE5
Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
}

XMLHttpRequest object is used to exchange data with the server.

Send a request to the server

To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object:

Xmlhttp.open ("GET", "Test1.txt", true);
Xmlhttp.send ();

Method

Describe

Open (method,url,async)

Specifies the type of request, the URL, and whether the request is processed asynchronously.

  • method: type of request; GET or POST
  • URL: The location of the file on the server
  • Async: True (asynchronous) or false (synchronous)

Send (string)

Sends the request to the server.

  • string: only for POST requests

GET or POST

GET is simpler and faster than POST, and can be used in most cases.

However, use the POST request in the following cases:

    • Unable to use cache file (update file or database on server)
    • Send a large amount of data to the server (POST has no data volume limit)
    • Post is more stable and more reliable than GET when sending user input with unknown characters
GET Request

A simple GET request:

Xmlhttp.open ("GET", "demo_get.asp", true);
Xmlhttp.send ();
POST Request

A simple POST request:

Xmlhttp.open ("POST", "demo_post.asp", true);
Xmlhttp.send ();

Try it yourself.

If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method:

Xmlhttp.open ("POST", "ajax_test.asp", true);
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Xmlhttp.send ("Fname=bill&lname=gates");

Try it yourself.

Method

Describe

setRequestHeader (header,value)

Adds an HTTP header to the request.

  • header: Name of the specified header
  • Value: The values of the specified header
URL-File server response on the server

To obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.

Property

Describe

ResponseText

Gets the response data in the form of a string.

Responsexml

Get the response data in XML form.

ResponseText Property

If the response from the server is not XML, use the ResponseText property.

Responsexml Property

If the response from the server is XML and needs to be parsed as an XML object

onReadyStateChange Events

When a request is sent to the server, we need to perform some response-based tasks.

The onreadystatechange event is triggered whenever the readyState changes.

The ReadyState attribute holds state information for XMLHttpRequest.

The following are three important properties of the XMLHttpRequest object:

Property

Describe

onReadyStateChange

The function (or function name) is called whenever the ReadyState property is changed.

ReadyState

The state of being xmlhttprequest. Vary from 0 to 4.

  • 0: Request not initialized
  • 1: Server Connection established
  • 2: Request received
  • 3: In Request processing
  • 4: The request is complete and the response is ready

Status

$: "OK"

404: Page Not Found

Using the Callback function

The callback function is a function that is passed as an argument to another function.

function MyFunction ()

{

Loadxmldoc ("Ajax_info.txt", function ()

{

if (xmlhttp.readystate==4 && xmlhttp.status==200)

{

document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;

}

});

}

JSON : JavaScript Object Notation ( J Ava S Cript O bject N otation ).

JSON is the syntax for storing and exchanging text information. Similar to XML.

JSON smaller, faster, and easier to parse than XML.

{

"Employees": [

{"FirstName": "Bill", "LastName": "Gates"},

{"FirstName": "George", "LastName": "Bush"},

{"FirstName": "Thomas", "LastName": "Carter"}

]

}

JSON-Convert to JavaScript object

The JSON text format is syntactically identical to the code that creates the JavaScript object.

Because of this similarity, the JavaScript program can use the built-in eval () function to generate native JavaScript objects with JSON data without a parser.

JSON syntax is a subset of JavaScript syntax.

JSON Syntax rules

JSON syntax is a subset of the JavaScript object notation syntax.

    • Data in name/value pairs
    • Data is separated by commas
    • Curly braces Save Object
    • Square brackets Save Array
JSON Name/value pairs

The writing format for JSON data is: name/value pairs.

Name/value pairs include the field name (in double quotation marks), followed by a colon, and then the value:

SON value

The JSON value can be:

    • Number (integer or floating point)
    • String (in double quotes)
    • Logical value (TRUE or FALSE)
    • Array (in square brackets)
    • Object (in curly braces)
    • Null
    • The file type of the JSON file is ". JSON"
    • The MIME type of JSON text is "Application/json"
JSON file JSON instance-an object from a string

Create a JavaScript string that contains the JSON syntax:

var txt = ' {' Employees ': [' +
' {' firstName ': ' Bill ', ' lastName ': ' Gates '}, ' +
' {' firstName ': ' George ', ' lastName ': ' Bush '}, ' +
' {' firstName ': ' Thomas ', ' lastName ': ' Carter '}]} ';

Because JSON syntax is a subset of JavaScript syntax, the JavaScript function eval () can be used to convert JSON text to JavaScript objects.

The eval () function uses the JavaScript compiler to parse the JSON text and then generate the JavaScript object. You must enclose the text in parentheses in order to avoid syntax errors:

var obj = eval ("(" + txt + ")");

The eval () function compiles and executes any JavaScript code. This hides a potential security issue.

Using the JSON parser to convert JSON to JavaScript objects is a safer practice. The JSON parser only recognizes JSON text and does not compile the script.

In the browser, this provides native JSON support, and the JSON parser is faster.

Native JSON support is included in both the new browser and the latest ECMAScript (JavaScript) standards.

Web Browser Support

Web Software Support

  • Firefox (Mozilla) 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
  • Jquery
  • Yahoo UI
  • Prototype
  • Dojo
  • ECMAScript 1.5

<script type= "Text/javascript" >

var txt = ' {' Employees ': [' +

' {' firstName ': ' Bill ', ' lastName ': ' Gates '}, ' +

' {' firstName ': ' George ', ' lastName ': ' Bush '}, ' +

' {' firstName ': ' Thomas ', ' lastName ': ' Carter '}]} ';

obj = json.parse (txt);

document.getElementById ("FName"). Innerhtml=obj.employees[1].firstname

document.getElementById ("LName"). Innerhtml=obj.employees[1].lastname

</script>

Ajax and JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.