AJAX = Asynchronous JavaScript and XML. In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
http://jqfundamentals.com/chapter/ajax-deferreds
url: '/data/people.json',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(options);
Example2 is about $.ajax() method:
$.ajax({
url: '/data/people.json',
dataType: 'json',
success: function( resp ) {
$( '#target').html( resp.people[0].name );
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
Ngầm định, request gửi về server dưới dạng GET, nếu muốn gửi POST request thì thêm tham số
ví dụ:
On selecting ‘Football’ in the first dropdown list
jQuery.get()
jQuery.each()
Wikipedia : JSON
hàm jQuery.each trên, ngoài duyệt qua phần tử mảng còn duyệt qua các phần tử bên trong một object, ví dụ:
ví dụ có data sau:
var data = [{"deviceId":"8030111111111","nodeIds":"000001","zoneID":3},{"deviceId":"8030111111111","nodeIds":"000002","zoneID":4}]
và gọi hàm
$.each(data, function (i, item) {
}
=>i = 0, item = {"deviceId":"8030111111111","nodeIds":"000001","zoneID":3}
i = 1, item = {"deviceId":"8030111111111","nodeIds":"000002","zoneID":4}
Do thẻ td không có 1 thuộc tính value.
Use
$("td").html() // to fetch html
$("td").html("<span> Hello World </span>") // to set html
$("td").text() // to fetch plain text
$("td").text("Hello World") // to set plain text
.html() or .text() or .prependor .append and more
Dù sao, hàm.val() chỉ làm việc trên các inputs mà có value="...." attribute.
If you want to prop the Cell with some data use .data("key","value") which can be accessed at any point by calling .data("key");
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script>
</head>
<body>
<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>
</body>
</html>
Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
jQuery provides several methods for AJAX functionality.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Lưu ý:
$("selector").each(function)
=> gọi hàm function với mỗi phần tử có cùng tên 'selector'
$("selector").click(function)
=> đăng ký hàm xử lý sự kiện click (có thể cả với change, change focus, focus mouseover, mouseover, ..) với onclick handler.
1. Các hàm jQuery AJAX
AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
The following table lists all the jQuery AJAX methods:
Method | Description |
---|---|
$.ajax() | Performs an async AJAX request |
$.ajaxPrefilter() | Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax() |
$.ajaxSetup() | Sets the default values for future AJAX requests |
$.ajaxTransport() | Creates an object that handles the actual transmission of Ajax data |
$.get() | Loads data from a server using an AJAX HTTP GET request |
$.getJSON() | Loads JSON-encoded data from a server using a HTTP GET request |
$.getScript() | Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request |
$.param() | Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests) |
$.post() | Loads data from a server using an AJAX HTTP POST request |
ajaxComplete() | Specifies a function to run when the AJAX request completes |
ajaxError() | Specifies a function to run when the AJAX request completes with an error |
ajaxSend() | Specifies a function to run before the AJAX request is sent |
ajaxStart() | Specifies a function to run when the first AJAX request begins |
ajaxStop() | Specifies a function to run when all AJAX requests have completed |
ajaxSuccess() | Specifies a function to run when an AJAX request completes successfully |
load() | Loads data from a server and puts the returned data into the selected element |
serialize() | Encodes a set of form elements as a string for submission |
serializeArray() | Encodes a set of form elements as an array of names and values |
2. Hàm jQuery load()
The jQuery load() method is a simple, but powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load.
The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
The optional callback parameter is the name of a function to be executed after the load() method is completed. It is a callback function that runs when the load() method is completed. The callback function can have different parameters:
- responseTxt - contains the resulting content if the call succeeds
- statusTxt - contains the status of the call
- xhr - contains the XMLHttpRequest object
Example
$("#div1").load("demo_test.txt");
$("#div1").load("demo_test.txt #p1");
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
3. Các hàm Query - AJAX get() & post()
The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.
Two commonly used methods for a request-response between a client and server are: GET and POST.
- GET - Requests data from a specified resource
- POST - Submits data to be processed to a specified resource
3.1 jQuery $.get()
The $.get() method requests data from the server with an HTTP GET request.
Syntax:
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.get() method to retrieve data from a file on the server:Example
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of $.get() is the URL we wish to request ("demo_test.asp").
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test.asp"):
<%
response.write("This is some text from an external ASP file.")
%>
$.get(URL,data,function(data,status,xhr),dataType)
Parameter
|
Description
|
URL
|
Required. Specifies the URL you wish to request
|
data
|
Optional. Specifies data to send to the server along with the request
|
function(data,status,xhr)
|
Optional. Specifies a function to run if the request succeeds
Additional parameters:
|
dataType
|
Optional. Specifies the data type expected of the server response.
By default jQuery performs an automatic guess.
Possible types:
|
3.2 jQuery $.post()
The $.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.post() method to send some data along with the request:
Example
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of $.post() is the URL we wish to request ("demo_test_post.asp").
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo_test_post.asp" reads the parameters, processes them, and returns a result.
The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test_post.asp"):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>
4. Hàm jQuery ajax()
Example
Change the text of a <div> element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
Definition and Usage
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
Syntax
$.ajax({name:value, name:value, ... })
OR:
jQuery.ajax( options )
OR
$.ajax( url[,options] )
OR$.ajax({ url: url, data: data, success: success, dataType: dataType });OR
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A1165 : 5 }
$.ajax({ url: url, method: 'GET', success: function (data) { if (successFunction) { successFunction(data); } }, error: function (data) { console.log('error'); }, timeout:5000, }); $.ajax({ url: url, method: 'POST', data: myKeyVals success: function (data) { if (successFunction) { successFunction(data); } }, error: function (data) { console.log('error'); }, timeout:5000, async: false });The parameters specifies one or more name/value pairs for the AJAX request.
Possible names/values in the table below:
some name:value pair in options parameter likes following:
Property | Description |
---|---|
url | A string containing the URL to which the request is sent. |
dataType | The format of the response data (e.g. json , xml , html ). |
beforeSend | A callback function that is executed before we send the request. Here, this function triggers the code that shows the loader. |
Example1 about options of jQuery.ajax() method:
var options = {url: '/data/people.json',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(options);
Example2 is about $.ajax() method:
$.ajax({
url: '/data/people.json',
dataType: 'json',
success: function( resp ) {
$( '#target').html( resp.people[0].name );
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
Name | Value/Description |
---|---|
async | A Boolean value indicating whether the request should be handled asynchronous or not. Default is true |
beforeSend(xhr) | A function to run before the request is sent |
cache | A Boolean value indicating whether the browser should cache the requested pages. Default is true |
complete(xhr,status) | A function to run when the request is finished (after success and error functions) |
contentType | The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded" |
context | Specifies the "this" value for all AJAX related callback functions |
data | Specifies data to be sent to the server |
dataFilter(data,type) | A function used to handle the raw response data of the XMLHttpRequest |
dataType | The data type expected of the server response. |
error(xhr,status,error) | A function to run if the request fails. |
global | A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true |
ifModified | A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false. |
jsonp | A string overriding the callback function in a jsonp request |
jsonpCallback | Specifies a name for the callback function in a jsonp request |
password | Specifies a password to be used in an HTTP access authentication request. |
processData | A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true |
scriptCharset | Specifies the charset for the request |
success(result,status,xhr) | A function to be run when the request succeeds |
timeout | The local timeout (in milliseconds) for the request |
traditional | A Boolean value specifying whether or not to use the traditional style of param serialization |
type | Specifies the type of request. (GET or POST) |
url | Specifies the URL to send the request to. Default is the current page |
username | Specifies a username to be used in an HTTP access authentication request |
xhr | A function used for creating the XMLHttpRequest object |
5. Ví dụ về ajax() jQuery trong java
5.1 jQuery AJAX JSP Servlet Java Example<script type="text/javascript"> $(document).ready(function() { $('#userName').blur(function() { $.ajax({ url : 'GetUserServlet', data : { userName : $('#userName').val() }, success : function(responseText) { $('#ajaxGetUserServletResponse').text(responseText); } }); }); }); </script> <form>Enter Your Name: <input type="text" id="userName" /></form> <br/><br/> <strong>Ajax Response</strong>: <div id="ajaxGetUserServletResponse"></div>Khi hộp văn bản mất đi focus thì sự kiện blur xảy ra (gần giống sự kiện change) và hàm ajax được gọi, nó gửi request về servlet và lấy dữ liệu cập nhật cho thẻ div có id=ajaxGetUserServletResponse.
Ngầm định, request gửi về server dưới dạng GET, nếu muốn gửi POST request thì thêm tham số
type:
"POST"
ví dụ:
<script type="text/javascript"> $(document).ready(function() { $('#userName').blur(function() { $.ajax({ type: "POST", url : 'GetUserServlet', data : { userName : $('#userName').val() }, success : function(responseText) { $('#ajaxGetUserServletResponse').text(responseText); } }); }); }); </script>5.2 Ajax Cascading DropDownList in JSP & Servlet using JQuery and JSON
Jsp Page
<html> <head> <title>AJAX in Servlet using JQuery and JSON</title> <script src="js/jquery-1.11.1.js" type="text/javascript"></script> <script> $(document).ready(function() { $('#sports').change(function(event) { var sports = $("select#sports").val(); $.get('JsonServlet', { sportsName : sports }, function(response) { var select = $('#player'); select.find('option').remove(); $.each(response, function(index, value) { $('<option>').val(value).text(value).appendTo(select); }); }); }); }); </script> </head> <body> <h3>AJAX in Servlet using JQuery and JSON</h3> Select Favorite Sports: <select id="sports"> <option>Select Sports</option> <option value="Football">Football</option> <option value="Cricket">Cricket</option> </select> <br /> <br /> Select Favorite Player: <select id="player"> <option>Select Player</option> </select> </body> </html>
Servlet
package com.action; import java.io.IOException; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sportsName = request.getParameter("sportsName"); List<String> list = new ArrayList<String>(); String json = null; if (sportsName.equals("Football")) { list.add("Lionel Messi"); list.add("Cristiano Ronaldo"); list.add("David Beckham"); list.add("Diego Maradona"); } else if (sportsName.equals("Cricket")) { list.add("Sourav Ganguly"); list.add("Sachin Tendulkar"); list.add("Lance Klusener"); list.add("Michael Bevan"); } else if (sportsName.equals("Select Sports")) { list.add("Select Player"); } json = new Gson().toJson(list); response.setContentType("application/json"); response.getWriter().write(json); } }
Web.xml
Servlet mapping should be done in web.xml as shown below
<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>JsonServlet</servlet-name> <servlet-class>com.action.JsonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JsonServlet</servlet-name> <url-pattern>/JsonServlet/*</url-pattern> </servlet-mapping>
Demo
On selecting ‘Football’ in the first dropdown list
Reference
Ở đây sử dụng hàm jQuery $.get(URL,data,function(data)
Dữ liệu trả về được dùng để tạo các <option></option> dùng hàm
jQuery.each( array, callback )
- arrayType: ArrayThe array to iterate over.
- callbackThe function that will be executed on every object.
hàm jQuery.each trên, ngoài duyệt qua phần tử mảng còn duyệt qua các phần tử bên trong một object, ví dụ:
// OBJECTS
var obj = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5
};
$.each(obj, function (index, value) {
console.log(value);
});
// Outputs: 1 2 3 4 5
6. Các hàm jQuery AJAX khác
6.1 $.each(data, function (i, item)
hàm này sẽ duyệt dữ liệu của 1 mảng json hoặc 1 object và trả về dữ liệu ở dạng chỉ số và value.ví dụ có data sau:
var data = [{"deviceId":"8030111111111","nodeIds":"000001","zoneID":3},{"deviceId":"8030111111111","nodeIds":"000002","zoneID":4}]
và gọi hàm
$.each(data, function (i, item) {
}
=>i = 0, item = {"deviceId":"8030111111111","nodeIds":"000001","zoneID":3}
i = 1, item = {"deviceId":"8030111111111","nodeIds":"000002","zoneID":4}
6.2. Dùng .html() cùng với selector để get/set HTML:
$('#detailInfo').html('changed value');Do thẻ td không có 1 thuộc tính value.
Use
$("td").html() // to fetch html
$("td").html("<span> Hello World </span>") // to set html
$("td").text() // to fetch plain text
$("td").text("Hello World") // to set plain text
.html() or .text() or .prependor .append and more
Dù sao, hàm.val() chỉ làm việc trên các inputs mà có value="...." attribute.
If you want to prop the Cell with some data use .data("key","value") which can be accessed at any point by calling .data("key");
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script>
</head>
<body>
<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>
</body>
</html>
$('#'DIV2).html(divContent )
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>world!</b>");
});
});
</script>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
0 comments:
Post a Comment