domingo, 7 de septiembre de 2014

Parametros de llamada AJAX jquery bien explicado

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
4 down vote accepted
dataType:
The type of data that you're expecting back from the server.
contentType:
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
----
contentType is used to determine how the payload has to be sent to the server as request parameters or as request body.

dataType is used to tell jQuery what is the return type of the request - to determine how to process the response text before it is sent the the handler methods

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
*****************
From the documentation:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
and:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
http://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
*****************

1.1 Propiedades de los llamados Ajax.

La función Ajax de JQuery recibe un JSON el cuál posee varias propiedades que enumeraremos a continuación.
  • type: Tipo de llamada que se ejecutara por defecto es GET.
  • url: Ruta a la cual se le ejecutara la llamada.
  • data: Datos que se enviaran al servidor, se envía un string con formato de JSON.
  • contentType: Tipo de datos que van a ser enviara al servidor.
  • dataType: Tipo de dato que se espera recibir desde el servidor . Jquery lo interpreta con los MIME types que el soporta. Los valores válidos para esta propiedad son los siguientes: (xml,html,script,json,jsop,text)
  • success:  Función ejecutada cuando la llamada Ajax fue satisfactoria.
  • error: Función a ser ejecutada si la llamada Ajax no fue satisfactoria.
  • async: Propiedad que define si la llamada Ajax es asíncrona o no, por defecto esta propiedad es verdadera.
Estas definiciones serán utilizadas posteriormente y es importante conocer su significado.
- See more at: http://7sabores.com/blog/consumir-un-webservice-net-jquery#sthash.vEl1KKTC.dpuf

http://7sabores.com/blog/consumir-un-webservice-net-jquery
*******************
contentType Se usa cuando se mandan datos a los servidores a modo de encabezado. String: "application/x-www-form-urlencoded" funciona perfectamente
data Se usa para especificar datos a mandar. Estos tienen la siguiente forma: foo=bar&foo2=bar2;. Si los datos a enviar son un vector(array) jQuery los convierte a varios valores con un mismo nombre (si foo["alt1","alt2"], foo="alt1"&foo="alt2";) Array / String con la forma antes mencionada. (un objeto que yo sepa tambien)
dataType Indica el tipo de datos que se van a llamar (YO: que se resiben del servidor). Si no se especifica jQuery automaticamente encontrará el tipo basado en el header del archivo llamado (pero toma mas tiempo en cargar, asi que especificalo u_u)
  • "xml": Devuelve un documento XML.
  • "html": Devuelve HTML con texto plano, y respeta las etiquetas.
  • "script": Evalua el JavaScript y devuelve texto plano.
  • "json": Evalua la respuesta JSON y devuelve un objeto Javascript 
http://www.cristalab.com/tutoriales/ajax-en-jquery-c226l/
*******************
jQuery
Nuestro último cliente será jQuery y lo cierto es que el más sencillo de todos.
La ventaja de jQuery frente a ASP.NET AJAX es que puede consumir servicios que no estén en la solución actual y además tampoco es necesario ningún cambio en el servicio web, es decir, no es necesario descomentar la línea que sí tuvimos que descomentar para trabajar con ASP.NET AJAX.
Además, para proyectos de ASP.NET MVC sólo tenemos disponible está opción
$(document).ready(function () {
    var options = {
        type: "POST",
        url: "/WebService1.asmx/Saludar",
        data: "{ 'nombre': 'Sergio' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //do something...
        },
        error: function (jqXHR, textStatus, errorThrown) { //do something...
        }
    }
    $.ajax(options);
});

Lo más relevante del este código es:
  • Se utiliza JSON para la llamada según indica el parámetro contentType.
  • Se pasan los datos en la propiedad data, de nuevo como un objeto JSON pero en una cadena.
  • El nombre del parámetro es case-sensitive, así que nombre funcionará pero Nombre fallará.
  • Se espera que la respuesta sea en formato JSON según indica el parámetro dataType.
Si quisiéramos llamar al método SaludarPersona que recibe un objeto del tipo Persona, habría que escribir lo siguiente en la propiedad data:
data: "{ 'persona' : { 'Nombre' : 'Sergio' , 'Apellidos' : 'León' } }",

http://panicoenlaxbox.blogspot.com/2011_12_01_archive.html
**************************

1 comentario:

  1. El Blog De La Programacion Evolutiva: Parametros De Llamada Ajax Jquery Bien Explicado >>>>> Download Now

    >>>>> Download Full

    El Blog De La Programacion Evolutiva: Parametros De Llamada Ajax Jquery Bien Explicado >>>>> Download LINK

    >>>>> Download Now

    El Blog De La Programacion Evolutiva: Parametros De Llamada Ajax Jquery Bien Explicado >>>>> Download Full

    >>>>> Download LINK JO

    ResponderEliminar