Sto cercando di capire come creare un oggetto JSON in JavaScript. Questo oggetto JSON verrà passato a una chiamata ajax JQuery. Attualmente sto codificando il mio JSON e faccio la mia chiamata JQuery come mostrato qui:JavaScript - Creazione dell'oggetto JSON
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"comments":"test","priority":"1"}',
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Questo approccio funziona. Ma ho bisogno di creare dinamicamente il mio JSON e passarlo alla chiamata JQuery. Tuttavia, non riesco a capire come creare dinamicamente l'oggetto JSON. Attualmente, sto provando quanto segue senza fortuna:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: json,
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Qualcuno può dirmi per favore cosa sto facendo male? Ho notato che con la seconda versione, il mio servizio non è nemmeno stato raggiunto.
Grazie
si fa a ottenere eventuali errori JavaScript? – SLaks
Punto eccellente: prova a eseguirlo con il debugger di Firebug attivato e guarda cosa ottieni. –
Non ricevo errori JavaScript. Tuttavia, il gestore di eventi di errore nella mia chiamata $ .ajax viene attivato. – user208662