Request data
We can use GET or POST to request data from the backend. Here, we use PHP as an example. Assume that the test page age. php is used to return the age information. The content is:
if(isset($_REQUEST['name']) && $_REQUEST['name'] == 'stephen') { echo '23';}
The content of the current page is:
<div> <a href="age.php">stephen</a> <span>age : </span> <span id="sex"></span></div>
We hope to obtain the age information without refreshing the page after clicking tag. First, use the GET method to request data:
GET Method
$('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); }); });
Click the tab. The current page is:
Data Request successful. We 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 it is changed from the get method to the post method.
Here we can also use the load method to simplify the Code:
$('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 Ajax technology, you can obtain data from the backend and send data to the backend. A common scenario is asynchronous form submission. Here we take user verification as an example:
<form action="validate.php"> username:<input id="username" name="username" type="text" /> password:<input id="password" name="password" type="text" /> <input value="submit" type="submit" /></form>
Assume that the verification is successful when the username is Stephen Lee and the password is 123456. Otherwise, the test page validate. php is:
if($_REQUEST['username'] == 'stephenlee' && $_REQUEST['password'] == '123456') { echo 'pass';} else { echo 'fail';}
Use get to send data to the backend for verification:
$('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); }); });
After the error username is entered, the result is:
Enter the correct username, and the result is:
If the post method is used to send data in the same way, we will not go into details.