Request data
We can use GET, POST two ways to request data backwards, here in PHP, for example, suppose there is a test page age.php, used to return age information, the content is:
if (isset ($_request[' name ')) && $_request[' name '] = = ' Stephen ') {
echo ';
}
The current page content is:
<div>
<a href= "age.php" >stephen</a>
<span>age: </span>
<span id= "Sex "></span>
</div>
We would like to click on the a label, without refreshing the page to get age information. First request data in Get mode:
Get mode
$ (' a '). Click (function (e) {
e.preventdefault ();//
var URL = $ (this). attr (' href '),
name = $ (this). Text () ,
requestdata = {' name ': name};
$.get (URL, requestdata, function (data) {
$ (' #sex '). HTML (data);};
});
After clicking on the A tab, the current page is:
The data request was successful. Let's use the POST method to test:
POST method
$ (' a '). Click (function (e) {
e.preventdefault ();//
var URL = $ (this). attr (' href '),
name = $ (this). Text (),
requestdata = {' name ': name};
$.post (URL, requestdata, function (data) {
$ (' #sex '). HTML (data);};
});
The code is almost the same, but the Get method becomes the Post method.
Here we can actually simplify the code with the Load method:
$ (' a '). Click (function (e) {
e.preventdefault ();
var url = $ (this). attr (' href '),
name = $ (this). Text (),
requestdata = {' name ': name};
$ (' #sex '). Load (URL, requestdata);
});
Send data
In addition to using Ajax technology to get data from the back end, you can also send data backwards, often by asynchronously submitting a form, with user authentication as an example:
<form action= "validate.php" >
username:<input id= "username" name= "username" type= "text"/>
Password:<input id= "password" name= "password" type= "text"/> <input "submit" value=
"Submit" type=
</form>
If the user name is Stephenlee, the password is 123456 when the validation passes, or fails, the test page validate.php:
if ($_request[' username '] = = ' Stephenlee ' && $_request[' password '] = = ' 123456 ') {
echo ' pass ';
C8/>echo ' fail ';
}
Send data to back-end validation using GET method:
$ (' form '). Submit (function (e) {
e.preventdefault ();//
var URL = $ (this). attr (' action '),
username = $ (' Input[name= "username"). Val (),
password = $ (' input[name= ' password '] '). Val (),
requestdata = {' username ': Username, ' Password ': password};
$.get (URL, requestdata, function (result) {
alert (result);
});
Enter the wrong username after Lucas, the result is:
After you enter the correct username Stephenlee, the result is:
Use post to send data in the same way, no longer repeat.