Javascript
var datos = $('form').serializeArray();
var usuarioSup = {
name: "usuarioSupervisor",
value: "abc"
};
var passwordSup = {
name: "passwordSupervisor",
value: "xxx"
};
datos.push(usuarioSup);
datos.push(passwordSup);
jqxhr2 = $.ajax({
type: "POST",
data: datos,
dataType: "json",
url: "@Url.Action(@Model.Accion, @Model.Controlador)",
beforeSend: function () {
}
}).fail(function (jqXHR, textStatus) {
$.unblockUI();
$("#mensaje").html("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#mensaje").html(data.Mensaje);
if (data.Codigo != "err_sup") {
$("#div_supervision").hide();
$("#@ViewBag.boton").removeProp("disabled");
}
});
MVC
[HttpPost]
public ActionResult Ejecutar(ConsultaViewModel modelo, string usuarioSupervisor, string passwordSupervisor)
{
return null;
}
Mostrando entradas con la etiqueta ajax. Mostrar todas las entradas
Mostrando entradas con la etiqueta ajax. Mostrar todas las entradas
Utilizar Ajax en C# [Funciona!]
Importar esta librería:
using System.Web.Script.Serialization;
Crear la clase DTO:
public class PersonaDTO
{
public string Nombre { get; set; }
public string Apellido { get; set; }
}
Crear el ActionResult:
[HttpGet]
public ActionResult Buscar(int param)
{
var x = new Persona();
x.Nombre = "Juana";
x.Apellido = "Perez";
return Json(x, JsonRequestBehavior.AllowGet);
}
Agregar el código javascript en la vista:
<script>
$(function () {
$.ajax({
data: { 'param': 123 },
url: "@Url.Action("Buscar", "Prueba")",
type: 'GET',
cache: false,
success: function (response) {
alert(response.Nombre);
},
error: function (a, b) {
alert("error fatal");
alert(a.responseText);
}
});
});
</script>
using System.Web.Script.Serialization;
Crear la clase DTO:
public class PersonaDTO
{
public string Nombre { get; set; }
public string Apellido { get; set; }
}
Crear el ActionResult:
[HttpGet]
public ActionResult Buscar(int param)
{
var x = new Persona();
x.Nombre = "Juana";
x.Apellido = "Perez";
return Json(x, JsonRequestBehavior.AllowGet);
}
Agregar el código javascript en la vista:
<script>
$(function () {
$.ajax({
data: { 'param': 123 },
url: "@Url.Action("Buscar", "Prueba")",
type: 'GET',
cache: false,
success: function (response) {
alert(response.Nombre);
},
error: function (a, b) {
alert("error fatal");
alert(a.responseText);
}
});
});
</script>
Internal Server Error 500 al intentar ejecutar un web service
descomentar la siguiente línea del web service:
<System.Web.Script.Services.ScriptService()> _
<System.Web.Script.Services.ScriptService()> _
Llamado a un webservice asmx con AJAX
Código .NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
<WebMethod> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Sub ObtenerChoiceListItems2(ByVal cobnamtab As String, ByVal filtro As String)
Dim js As New JavaScriptSerializer()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Dim d As String = "{ " +
"'datos': { " +
"'items': [{ " +
" 'coddestab': '5', " +
" 'deslartab': 'DESC ITEM 5' " +
" }, { " +
" 'coddestab': '10', " +
" 'deslartab': 'DESC ITEM 10' " +
" }, { " +
" 'coddestab': '15', " +
" 'deslartab': 'DESC ITEM 15' " +
"}]" +
"}" +
"}"
Context.Response.Write(js.Serialize(d))
End Sub
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
<WebMethod> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Sub ObtenerChoiceListItems2(ByVal cobnamtab As String, ByVal filtro As String)
Dim js As New JavaScriptSerializer()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Dim d As String = "{ " +
"'datos': { " +
"'items': [{ " +
" 'coddestab': '5', " +
" 'deslartab': 'DESC ITEM 5' " +
" }, { " +
" 'coddestab': '10', " +
" 'deslartab': 'DESC ITEM 10' " +
" }, { " +
" 'coddestab': '15', " +
" 'deslartab': 'DESC ITEM 15' " +
"}]" +
"}" +
"}"
Context.Response.Write(js.Serialize(d))
End Sub
Código javascript:
function cargarChoiceList(vNombreCombo, vCobnamtab)
{
jQuery.support.cors = true;
rndAux = '&random=' + Math.floor(Math.random()*9999999999);
jqxhr2 = jQuery.ajax({
type:"GET",
data:{ cobnamtab: vCobnamtab,
filtro:"",
rnd: rndAux},
dataType:"json",
url:"http://" + window.self.location.hostname + "/wsX/Parametros.asmx/ObtenerChoiceListItems2",
beforeSend:function(){
}
}).fail(function(jqXHR, textStatus){
alert("Error: " + "Status: "+
jqXHR.status +" detalle: "+ textStatus +
" detalle: "+ jqXHR.responseText);
}).success(function(data){
var v = getJSON(data);
$("[name=" + vNombreCombo + "]").empty();
for (i=0; i<v.datos.items.length; i++)
{
$("[name=" + vNombreCombo + "]").append($('<option>', {
value: v.datos.items[i]["coddestab"],
text : v.datos.items[i]["deslartab"]
}));
}
});
}
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
Ejemplo de llamado:
cargarChoiceList('WFF-SINO3', 'BANCOS');
Enviar datos desde javascript hacia un controller con AJAX en MVC
Método #1: Enviar form como JSON y otros parametros
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
Controller
Método #4: Enviar el form serializado
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
}
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
De esta forma se puede enviar el modelo desde la vista hacia un controller, cualquiera sea su estructura y complejidad.
Funciona con POST y GET, en este ejemplo se utiliza POST.
*** Tener en cuenta que utilizando este método NO se envían los datos modificados manualmente en el formulario o los datos cargados mediante javascript. Para poder hacer esto, utilizar el método 3 ***
Código en la View
Formulario:
@using Creditos.ViewModels.Liquidaciones
@model RefinanciacionArrendamientoVM
...
...
...
Llamado Ajax
var model = JSON.parse('@Html.Raw(Json.Encode(Model))');
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
[HttpPost]
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
CORS en llamados Ajax (Cross Origin Resource Sharing) en jQuery
Cuando se realiza un llamado Ajax desde una página html (o .vm, o .aspx, etc), en realidad se está realizando una llamada CORS (Cross Origin Resource Sharing).
Esto es porque la invocación se realiza desde el equipo del usuario hacia un servidor (por ejemplo Xdesa).
Por defecto, y por cuestiones de seguridad, los llamados CORS no están habilitados, y si se realizan se genera una excepción con el texto "No Transport".
Para habilitar ejecuciones CORS, a partir de la versión 1.4.1 de jQuery es necesario realizar esta configuración:
jQuery.support.cors = true;
La versión previa a 1.4.1 (inclusive), no requiere este setting.
Esto es porque la invocación se realiza desde el equipo del usuario hacia un servidor (por ejemplo Xdesa).
Por defecto, y por cuestiones de seguridad, los llamados CORS no están habilitados, y si se realizan se genera una excepción con el texto "No Transport".
Para habilitar ejecuciones CORS, a partir de la versión 1.4.1 de jQuery es necesario realizar esta configuración:
jQuery.support.cors = true;
La versión previa a 1.4.1 (inclusive), no requiere este setting.
Invocar webservice jsonp con ajax y jquery
Este ejemplo utiliza NewtonSoft JSON que se puede bajar de acá: http://james.newtonking.com/json
En web.config del webservice:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
Página que invoca al servicio:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.11.0.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="btn1" type="button" value="ok" />
</div>
</form>
<script>
$(function() {
var host = "http://localhost:11245/webservice1/Clientes.asmx/ObtenerClientes";
$("#btn1").click(function() {
$.ajax({
type: 'GET',
url: host,
data: { prefix: $("#txtNombreT").val() },
dataType: "jsonp",
jsonpCallback: "funcion1",
crossDomain: true,
cache: false,
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
window.localJsonpCallback = function(json) {
if (!json.Error) {
alert(json[0].nombre);
}
else {
alert(json.Message);
}
}
});
//ojo!! esta funcion debe estar fuera del document.ready!!
//o sino definirla como window.funcion1 = .... VER EJEMPLO ARRIBA
function funcion1(data) {
if (!data.Error) {
datos = data;
}
else {
alert(data.Message);
}
}
</script>
</body>
</html>
Código del webservice:
Ejemplo de lo que debe retornar:
funcion1([
{
"nombre": "Juan",
"documento": "23-10013"
},
{
"nombre": "Pedro",
"documento": "23-463"
},
{
"nombre": "Silvia",
"documento": "23-460"
},
{
"nombre": "Fernanda",
"documento": "23-10132"
},
{
"nombre": "Ricardo",
"documento": "2-21539085001"
}
]);
Public Class pers
Public nombre As String
Public documento As String
End Class
<WebMethod()> _
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Sub ObtenerClientes(ByVal prefix As String, ByVal callback As String)
'Mantis 25829 - rmeneses
'Dim personas As New List(Of String)()
Dim personas As New List(Of pers)()
Dim odb As New SqlDb
Dim nombre As String
odb.AbrirDB()
odb.BeginTran()
cifIO.cli.LeerClientesBusquedaIncrementalTodos(odb, prefix)
Dim s As String = ""
For i As Integer = 0 To odb.dt.Rows.Count - 1
nombre = CType(odb.dt.Rows(i).Item(3), String)
s = "{" & Chr(34) & "nombre" & Chr(34) & ": " & Chr(34) & nombre.Trim() & Chr(34) & ", " & _
Chr(34) & "documento" & Chr(34) & ": " & Chr(34) & odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1) & "-" & odb.dt.Rows(i).Item(2) & Chr(34) & "}"
Dim p As pers = New pers()
p.nombre = nombre.Trim()
p.documento = odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1)
personas.Add(p)
Next
Dim sb As New StringBuilder()
sb.Append(callback & "(")
sb.Append(JsonConvert.SerializeObject(personas, Formatting.Indented))
sb.Append(");")
odb.CommitTran()
odb.CerrarDB()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.Write(sb.ToString())
Context.Response.End()
End Sub
En web.config del webservice:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
</system.web>
Página que invoca al servicio:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.11.0.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="btn1" type="button" value="ok" />
</div>
</form>
<script>
$(function() {
var host = "http://localhost:11245/webservice1/Clientes.asmx/ObtenerClientes";
$("#btn1").click(function() {
$.ajax({
type: 'GET',
url: host,
data: { prefix: $("#txtNombreT").val() },
dataType: "jsonp",
jsonpCallback: "funcion1",
crossDomain: true,
cache: false,
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
window.localJsonpCallback = function(json) {
if (!json.Error) {
alert(json[0].nombre);
}
else {
alert(json.Message);
}
}
});
//ojo!! esta funcion debe estar fuera del document.ready!!
//o sino definirla como window.funcion1 = .... VER EJEMPLO ARRIBA
function funcion1(data) {
if (!data.Error) {
datos = data;
}
else {
alert(data.Message);
}
}
</body>
</html>
Código del webservice:
Ejemplo de lo que debe retornar:
funcion1([
{
"nombre": "Juan",
"documento": "23-10013"
},
{
"nombre": "Pedro",
"documento": "23-463"
},
{
"nombre": "Silvia",
"documento": "23-460"
},
{
"nombre": "Fernanda",
"documento": "23-10132"
},
{
"nombre": "Ricardo",
"documento": "2-21539085001"
}
]);
Public Class pers
Public nombre As String
Public documento As String
End Class
<WebMethod()> _
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Sub ObtenerClientes(ByVal prefix As String, ByVal callback As String)
'Mantis 25829 - rmeneses
'Dim personas As New List(Of String)()
Dim personas As New List(Of pers)()
Dim odb As New SqlDb
Dim nombre As String
odb.AbrirDB()
odb.BeginTran()
cifIO.cli.LeerClientesBusquedaIncrementalTodos(odb, prefix)
Dim s As String = ""
For i As Integer = 0 To odb.dt.Rows.Count - 1
nombre = CType(odb.dt.Rows(i).Item(3), String)
s = "{" & Chr(34) & "nombre" & Chr(34) & ": " & Chr(34) & nombre.Trim() & Chr(34) & ", " & _
Chr(34) & "documento" & Chr(34) & ": " & Chr(34) & odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1) & "-" & odb.dt.Rows(i).Item(2) & Chr(34) & "}"
Dim p As pers = New pers()
p.nombre = nombre.Trim()
p.documento = odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1)
personas.Add(p)
Next
Dim sb As New StringBuilder()
sb.Append(callback & "(")
sb.Append(JsonConvert.SerializeObject(personas, Formatting.Indented))
sb.Append(");")
odb.CommitTran()
odb.CerrarDB()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.Write(sb.ToString())
Context.Response.End()
End Sub
JSONP en servidor Arduino - CrossDomain
Uso: Un sitio web alojado en el dominio X quiere obtener datos de un Arduino con Ethernet Shield alojado en el dominio Y.
JSONP es la forma de implementar llamados AJAX Cross Domain:
Referencias:
http://api.jquery.com/jQuery.ajax/
http://json-p.org/
http://www.funcion13.com/2012/04/12/como-realizar-peticiones-ajax-cross-domain-jsonp-jquery/
Test.php:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/funciones.js"></script>
</head>
<body>
<input id="detectar" type="button" value="Detectar...">
</body>
<script>
$(document).ready(function() {
$("#detectar").click(function() {
invocarAjax();
});
});
</script>
</html>
funciones.js
function arduinoEthernetComCallback(data)
{
alert("data es!!: " + data);
var j = eval('(' + data + ')');
alert(j["A5"]);
}
function invocarAjax()
{
rnd = '&random=' + Math.floor(Math.random()*9999999999);
$.ajax({
url : 'http://192.168.0.200:93?rnd='+rnd,
dataType : 'jsonp',
crossDomain : true
});
}
JSONP es la forma de implementar llamados AJAX Cross Domain:
Referencias:
http://api.jquery.com/jQuery.ajax/
http://json-p.org/
http://www.funcion13.com/2012/04/12/como-realizar-peticiones-ajax-cross-domain-jsonp-jquery/
Test.php:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/funciones.js"></script>
</head>
<body>
<input id="detectar" type="button" value="Detectar...">
</body>
<script>
$(document).ready(function() {
$("#detectar").click(function() {
invocarAjax();
});
});
</script>
</html>
funciones.js
function arduinoEthernetComCallback(data)
{
alert("data es!!: " + data);
var j = eval('(' + data + ')');
alert(j["A5"]);
}
function invocarAjax()
{
rnd = '&random=' + Math.floor(Math.random()*9999999999);
$.ajax({
url : 'http://192.168.0.200:93?rnd='+rnd,
dataType : 'jsonp',
crossDomain : true
});
}
Sketch:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0,200);
char callback[27] = "arduinoEthernetComCallback";
EthernetServer server(93);
void setup()
{
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n' && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
client.println();
client.print(callback);
client.print("('{");
for (int i=0; i<6; i++) {
client.print("\"A");
client.print(i);
client.print("\": ");
client.print(i*10);
if (i != 5) {
client.print(",");
}
}
client.println("}')");
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
client.stop();
}
}
Utilizar AJAX en .net con framework 3.0
Instalar ASPAJAXExtSetup.msi
Esto deja una dll en la siguiente ruta:
C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\System.Web.Extensions.dll
Esa dll es la que permite hacer el "using System.Web.Extensions", y es donde esta "System.Web.Script.Services.ScriptService" (lo que permite llamar al webservice desde un javascript con ajax, por ej)
Llamar a un webmethod de un WebService con jQuery
Versiones:
Visual Studio 2008
jquery-1.4.1.min.js
System.Web.Extensions.dll versión 3.5.0.0
Código C#
using System;
using System.Web.Services;
namespace wsX
{
/// <summary>
/// Descripción breve de Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string Prueba1(int param)
{
return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }";
}
}
}
Código html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery-1.4.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Prueba 1</title>
<body>
<script type="text/javascript">
$(document).ready(function()
{
jQuery.ajax({
type: "POST",
url: "http://localhost:2366/Service1.asmx/Prueba1",
data: "{'param': '123'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
cache: false,
success: function(response) {
var v = getJSON(response);
alert("Resultado: " + v.datos[0].nombre);
}
});
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
});
</script>
</body>
</html>
Visual Studio 2008
jquery-1.4.1.min.js
System.Web.Extensions.dll versión 3.5.0.0
Código C#
using System;
using System.Web.Services;
namespace wsX
{
/// <summary>
/// Descripción breve de Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string Prueba1(int param)
{
return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }";
}
}
}
Código html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery-1.4.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Prueba 1</title>
<body>
<script type="text/javascript">
$(document).ready(function()
{
jQuery.ajax({
type: "POST",
url: "http://localhost:2366/Service1.asmx/Prueba1",
data: "{'param': '123'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
cache: false,
success: function(response) {
var v = getJSON(response);
alert("Resultado: " + v.datos[0].nombre);
}
});
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
});
</script>
</body>
</html>
Ejecutar web service desde maquina remota (ERROR: The test form is only available for requests from the local machine)
Agregar estas líneas a web.config:
<configuration> <system.web> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> </system.web> </configuration>
<configuration> <system.web> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> </system.web> </configuration>
Cargar div mediante jQuery y ajax
jQuery.ajax({ url: a + '_' + trn + 'conSup.vm', async: false, cache: false, success: function(){
Importante!! Poner cache: false, sino sólo se ejecuta la 1ra vez.
Invocacion a ASP.NET mediante jQuery y Ajax
$.post('http://servidor/prueba1/Default.aspx', function(data) {
alert(data);
});
Suscribirse a:
Entradas (Atom)