Estoy tratando de enviar una cadena simple usando una solicitud de publicación de Ajax:
var user = { "name": name, "country": country, }; $.ajax({ type: 'POST', traditional: true, url: 'Default.aspx/Submit', data: JSON.stringify(user), contentType: "application/json; charset=utf-8", dataType: "text", success: function (msg) { alert("Success!"); }, error: function () { alert("Error!"); } });
[WebMethod] public static bool Submit(string json) { // do something return true; }
Lo puse:
string
, no un object
text
no json
pero todavía recibí este error del servidor:
llamada de servicio web no válida, valor faltante para el parámetro: json
Supongo que esto se debe a que no encuentra un nombre coincidente para el parámetro "json". Pero no entiendo cómo tengo que nombrar el parámetro de función si estoy enviando una cadena simple.
Este es el código que uso para publicar en una base de datos usando AJAX.
// Variable para retener solicitud var solicitud;
// Enlace al evento de envío de nuestro formulario $("#form1").submit(function(event){
// Abort any pending request if (request) { request.abort(); } //local variables var $form = $(this); // select and cache all the fields var $inputs = $form.find("input, select, button, textarea"); // Serialize the data in the form var serializedData = $form.serialize(); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to php file request = $.ajax({ url: yourdomain-asp-page, type: "post", data: serializedData }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ //replace form with feedback text // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); // Prevent default posting of form event.preventDefault();
});