Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

JQuery:Ajax

From Aino Wiki

Jump to: navigation, search

Introduzione

Teoria uso istruzione $.ajax

Chiamate ajax

Tabella parametri $.ajax

Tabella parametri del metodo $.ajax:

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

GET

Esempio 1 ($.ajax)

Segue particolare Javascript di esempio:
$.ajax({
        type: 'GET',
	url: 'api/Employees',
	dataType: 'json',
	success: function (data) {		
                    var strOut = JSON.stringify(data);
                    alert("Oggetto ricevuto:\n" + strOut);
	},
        error: function (xhr) {
                alert('Si è verificato un errore:\r\nStatus ' + xhr.status + '\r\nMessage: ' + xhr.statusText);                                    
        }
});

Esempio 2 ($.getJSON)

Si usa $.getJSON(uri). Esempio preso da: ocs.microsoft Web API

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Product App</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
        <script>
        var uri = 'api/products';
 
        $(document).ready(function () {
          // Send an AJAX request
          $.getJSON(uri)
              .done(function (data) {
                  // On success, 'data' contains a list of products.
                  // data è un Json che viene automaticamente deserializzato per la GET
                  // ogni elemento del vettore verrà messo in "item"
                  // "key" è l'indice numerico del vettore, il primo sarà 0
                $.each(data, function (key, item) {
                    // Add a list item for the product.
                    // .appendTo($('#products')) cerca un elemento nell'HTML che ha id="products" e accoda
                    // una stringa creata come indicato in "$(...qui...)"
                  $('<li>', { text: formatItem(item) }).appendTo($('#products'));
                });
              });
            /* 
Lato server, data è un array di Product così fatto:
 
    private Product[] products = new Product[]
    {
        new Product
        {
            Id = 1,
            Name = "Tomato Soup",
            Category = "Groceries",
            Price = 1 },
        new Product
        {
            Id = 2,
            Name = "Yo-yo",
            Category = "Toys",
            Price = 3.75M },
        new Product
        {
            Id = 3,
            Name = "Hammer",
            Category = "Hardware",
            Price = 16.99M }
    };
            */
        });
 
        function formatItem(item) {
            //In output restituisce una stringa!
            //item è automaticamente trasformato nel tipo Product (classe lato Server)
          return item.Name + ': $' + item.Price;
        }
 
        function find() {
            // Cerca un elemento HTML con id="prodId" ed il valore lo mette nella varibile 'id'
          var id = $('#prodId').val();
          $.getJSON(uri + '/' + id)
              .done(function (data) {
                $('#product').text(formatItem(data));
              })
              .fail(function (jqXHR, textStatus, err) {
                $('#product').text('Error: ' + err);
              });
        }
        </script>
    </head>
    <body>
        <div>
            <h2>All Products</h2>
            <ul id="products" />
        </div>
        <div>
            <h2>Search by ID</h2>
            <input type="text" id="prodId" size="5" />
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
 
    </body>
</html>

Due parametri fondamentali della $.getJSON:

  • .done(function (data)) 'data' è il JSON ricevuto
  • .fail(function (jqXHR, textStatus, err)) ...

Chiamata a Web API

Esempio di chiamata a WebAPI, perso qui. Per effettuare una GET, l'URL di esempio alla Web API è:

api/Employees
Esempio inserito nella pagina HTML
<!DOCTYPE html>
<html lang="it" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test chaimate Web API</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
 
            $('#btn').click(function () {
                $.ajax({
                    type: 'GET',
                    url: 'api/Employees',
                    dataType: 'json',
                    success: function (data) {
 
                        ulEmployees.empty();
                        $.each(data, function (index, val) {
                            var fullName = val.FirstName + ' ' + val.LastName;
                            ulEmployees.append('<li>' + fullName + '</li>')
 
                        });
                    }
                });
            });
 
            $('btnClear').click(function () {
                ulEmployeess.empty();
            });
 
        });
    </script>
    <style type="text/css"></style>
</head>
 
<body>
    <pre>
URL di questa pagina:   http://localhost/TestCallWEBAPI.html
Swagger qui:            http://localhost/swagger/ui/index
    </pre>
    <br />
    <p>
        <input type="button" id="btn" value="" />
        <input type="button" id="btnClear" value="Clear" />
    </p>
</body>
</html>

POST

Esempio passando dato strutturato

[Route("Auth/Login")]
[HttpPost]//[HttpGet]
public IHttpActionResult Login(UserLogin userLogin)
{
    // Codice
}
//-------------- Oggetto passato:
[DataContract]
public class UserLogin : IUserLogin
{
	/// <summary>
	/// Campo generato dal server
	/// </summary>
	[DataMember]
	public string PageID
	{
		get;
		set;
	}
	[DataMember]
	public string InputPageName
	{
		get;
		set;
	}
	/// <summary>
	/// Attributo obbligatorio autogenerato
	/// </summary>
	[DataMember]
	public int UserID
	{
		get;
		set;
	}
	[DataMember]
	public string UserName
	{
		get;
		set; }
	[DataMember]
	public string Password
	{
		get;
		set;
	}
}

Javascript:

function Login() {
	try {
		var userlogin = {
			"PageID": $('#hddPageId').val(),
				"InputPageName": "Login",
				"UserID": 0,
				"UserName": $('#TxtUserName').val(),
				"Password": $('#TxtPassword').val()
		}
		//alert(JSON.stringify(userlogin));
 
		$.ajax({
			type: 'POST',
			url: 'Auth/Login',
			dataType: 'json',
			contentType: 'application/json',
			data: JSON.stringify(userlogin),
			success: function (responseData) {
				try {
					var strResponseData = JSON.stringify(responseData);
					alert('Ritorno del Login:\r\n' + strResponseData);
 
					sessionStorage.setItem('accessToken', responseData.Token);
					// To retrieve:     sessionStorage.getItem('accessToken');
					// To remove:       sessionStorage.removeItem('accessToken');
				} catch (e) {
					alert(e.message);
				}
			},
			error: function (xhr) {
				alert('Si è verificato un errore:\nStatus ' + xhr.status
					+ '\nMessage: ' + xhr.statusText);
			}
		}); 
	} catch (e) {
		alert(e);
	} 
}

Mappa e Link


JQuery


C Sharp | HTML | CSS | JavaScript


Parole chiave:

Author