Jquery ajax returns json data for front-end and back-end interaction instances

Source: Internet
Author: User

This article describes how to use ajax in jquery to submit data and then use the website background to return data in json format based on the submitted data. Here is an example.

Let's take a look at the Demo code.

The Code is as follows: Copy code

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Ajax json test </title>

<Script language = "javascript" src = "./jquery-1.7.1.min.js"/> </script>
<Script language = "javascript" src = "./ajax_json.js"/> </script>

</Head>

<Body style = "font-family: Arial; line-height: 150%">
 
<A href = "javascript: getAllUsers ();"> get all user information </a> & nbsp;
 
<! -- Used to display returned results -->
<Div id = "users"> </div>
 
</Body>
</Html>

When we click to obtain all user information, it is displayed in div id = users.


JSON string returned by Ajax:
[{"UserId": 1, "userName": "Raysmond" },{ "userId": 2, "userName": "u96f7u5efau5764" },{ "userId": 3, "userName": "Rita"}]

The parsed result is:
UserId = 1
UserName = Raysmond
UserId = 2
UserName = Lei jiankun
UserId = 3
UserName = Rita

You may not understand the code above. Let's introduce it in detail now.

Code Section

The Code is as follows: Copy code

Index.html

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Ajax json test </title>

<Script language = "javascript" src = "./jquery-1.7.1.min.js"/> </script>
<Script language = "javascript" src = "./ajax_json.js"/> </script>

</Head>

<Body style = "font-family: Arial; line-height: 150%">
<H1> Ajax uses JSON for frontend and backend interaction <A href = "javascript: getAllUsers ();"> get all user information </a> <br/>
 
<! -- Used to display returned results -->
<Div id = "users"> </div>
</Body>
</Html> ajax_json.js

/**
* JQuery synchronous Ajax Encapsulation
*/
Function getJson (RequestData, URL ){
Var reJson;
$. Ajax ({
Type: 'post ',
Url: URL,
Data: RequestData,
Async: false, // set to synchronous for convenience
Cache: false,
Success: function (responseData ){
ReJson = responseData;
}
});
Return reJson;
}

/**
* Getting all user information
*/
Function getAllUsers (){
Var url = "./service. php ";
Var request = 'Action = get_all_users ';
// Obtain and parse from the backend. Because ajax is encapsulated above, synchronous return is used,
// Therefore, the returned data can be obtained successfully.
Var json = getJson (request, url );
Var users = eval ('+ json + ')');
 
Var usersHtml = '<br/> <span style = "color: red;"> JSON string returned by Ajax: </span> <br/>'
+ Json + '<br/> <span style = "color: red;"> the parsed result is: </span> <br/> ';
For (var I = 0; I <users. length; ++ I ){
UsersHtml + = 'userid = '+ users [I]. userId +' <br/>'
+ 'Username = '+ users [I]. userName +' <br/> ';
}
// Dynamically display the constructed HTML to the page using jQuery
('{Users'{.empty({.html (usersHtml );
}
Service. php

<? Php
// Accept the request parameters and select the operation based on the parameters
If (isset ($ _ POST ['action']) & $ _ POST ['action']! = ""){
Switch ($ _ POST ['action']) {
Case 'get _ all_users': getAllUsers (); break;
Default:
}
}

// Process the request: return all user information in JSON format
Function getAllUsers (){
$ Users = array (
Array ("userId" => 1, "userName" => "Raysmond "),
Array ("userId" => 2, "userName" => "Lei jiankun "),
Array ("userId" => 3, "userName" => "Rita ")
);
Echo json_encode ($ users );
}
?>

Related Article

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.