Estoy tratando de enviar algunos datos al backend usando la solicitud de publicación de ajax. Me gusta esto
$.ajax({ url: "/aa", dataType: 'text', type: 'post', contentType: 'application/x-www-form-urlencoded', data: input.value, success: function (result) { console.log("Success", input.value); }, error: function (data) { console.log(data); } });pero cuando quiero imprimir los datos de mi cuerpo como este, recibo undefined
console.log(requ.body.data);también uso analizador de cuerpo en el backend
app.use(bodyParser.raw())¿Por qué devuelve indefinido?
Espero que esto funcione
<script> $(document).ready(function () { //function will be called on button click having id btnsave $("#btnSave").click(function () { $.ajax( { type: "POST", //HTTP POST Method url: "Home/AddEmployee", // Controller/View data: { //Passing data Name: $("#txtName").val(), //Reading text box values using Jquery City: $("#txtAddress").val(), Address: $("#txtcity").val() } }); }); }); </script> in controller side [HttpPost] public ActionResult AddEmployee(EmpModel obj) { AddDetails(obj); return View(); }esto funciona, por favor dime si quieres que cree un violín
Controlador:
[HttpPost] public string Index900(string theValue) { try { throw new Exception("this is the Value" + theValue); } catch (Exception ex) { return ex.Message; } } public ActionResult Index() { return View(); }Vista:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script> $(function () { $("#theBtn").click(function () { var theValue = $("#theInput").val(); $.ajax({ url: "/Home/Index900", //changed this dataType: 'text', type: 'post', contentType: 'application/json', //changed this data: JSON.stringify({ theValue: theValue }), //changed this success: function (result) { //console.log("Success", input.value); //changed this alert(result); }, error: function (data) { //changed this //console.log(data); //changed this alert("error...") } }); }); }); </script> </head> <body> <div> <input type="button" id="theBtn" value="Click to start ajax" /> <input type="text" id="theInput" value="Some Value" /> </div> </body> </html>