In the previous article, the examples of data loading of <a href="//m.sbmmt.com/wiki/1495.html" target="_blank">jquery</a> Ajax
are all obtained from static files, and Ajax
The greater value lies in data transfer with the back-end server, dynamically requesting and sending data.
We can use GET and POST
to request data from the backend. Here we take PHP
as an example, assuming there is a test Page age.php
, used to return age information, the content is:
if(isset($_REQUEST['name']) && $_REQUEST['name'] == 'stephen') { echo '23'; }
The current page content is:
<p> <a href="age.php">stephen</a> <span>age : </span> <span id="sex"></span> </p>
a tag, get the age information without refreshing the page. First use the
GET method to request data:
$('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); }); });
a tag, the current page is:
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); }); });
get method is changed to
post method.
Here we can actually 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); });
Ajax technology to get it from the backend Data can also be sent to the backend. A common scenario is to submit a form asynchronously. Here is 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>
stephenlee, the verification passes when the password is
123456, otherwise it fails. The test page
validate.php is:
if($_REQUEST['username'] == 'stephenlee' && $_REQUEST['password'] == '123456') { echo 'pass'; } else { echo 'fail'; }
get method 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); }); });
lucas, the result is:
stephenlee, the result is:
post method is the same, so I won’t go into details.
The above is the detailed content of Analysis of jQuery Ajax Operation (2) Data Transfer. For more information, please follow other related articles on the PHP Chinese website!