简体   繁体   English

如何将数据从 controller 方法返回到 jquery ajax 帖子

[英]How to return data from controller method to a jquery ajax post

My Jquery ajax call -我的 Jquery ajax 通话 -

         var formdata = $('#emailrequest').serializeArray();

          // Ajax call to server
          $.ajax({
              url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
              type: 'POST',
              data: formdata,
              sucess: function(data) {
                  alert(data.sucess);
              },
              error: function() {
                  alert('error');
              }
              });//End Ajax

My controller -我的 controller -

    public ActionResult ProcessEmailrequest()
            {

              // some code

            // retun the response 
            return Json(new {success = true});

But all is get is error in alert.但是得到的只是警报中的错误。 Where am I going wrong?我哪里错了? Please help.请帮忙。 I just need to return a confimation from controller, be it any format.我只需要从 controller 返回一个确认,无论是任何格式。

You spelled success wrong so it will never hit.你拼错了成功,所以它永远不会命中。 It should work with the ActionResult but a JsonResult is better.它应该与 ActionResult 一起使用,但 JsonResult 更好。

         var formdata = $('#emailrequest').serializeArray();

      // Ajax call to server
      $.ajax({
          url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
          type: 'POST',
          data: formdata,
          success: function(data) {
              alert(data.sucess);
          },
          error: function() {
              alert('error');
          }
          });//End Ajax

Try to set your controller method return type to JsonResult instead of ActionResult, so:尝试将您的 controller 方法返回类型设置为 JsonResult 而不是 ActionResult,因此:

 public JsonResult ProcessEmailrequest()
 {
     // some code

     // retun the response 
     return Json(new {success = true});
 }

If that doesn't help set your ajax error function to receive following parameters:如果这无助于设置您的 ajax 错误 function 以接收以下参数:

 error: function (xhr, ajaxOptions, thrownError) {
      ...
 }

Then debug in browser and set a break point to error function and in the xhr object (responseText property) you'll be able to see exact error.然后在浏览器中调试并将断点设置为错误 function 和 xhr object(responseText 属性),您将能够看到确切的错误。

you shoudn't return json like that.你不应该这样返回 json 。 use [ ] instead of {}使用 [ ] 而不是 {}

public JsonResult ProcessEmailrequest()
 {
     // some code

     // retun the response 
     return Json(new [success = true]);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM