简体   繁体   English

函数不从ajax调用返回消息

[英]function not returning message from ajax call

I want my function, which does an ajax call to controller, to return message from response. 我希望我的函数,它对控制器执行ajax调用,从响应中返回消息。

I've tried this, but it doesnt work. 我试过这个,但它不起作用。 How can acchieve my goal? 如何才能达到我的目标? is there a better solution for this? 有更好的解决方案吗?

var exists = personExists ();

   if (exists != null) {
      alert('The person already exists');
      return;
   }

var personExists = function () {

   var exists = false;
   var errorMsg = null;

$.ajax({
      url: "@Url.Action("PersonExist", "Person")",
      type: "POST",
      dataType: 'json',
      data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
      async: false,
      contentType: "application/json",
      success: function (response) {
          if (response.exists) {
             exists = true;
             errorMsg = response.message;
          }
      }
 });

 if (exists)
   return errorMsg;

 return null;
};

You need to use a callback: 你需要使用回调:

function getErrorMessage(message) {
    //do whatever
}

Inside the AJAX request: 在AJAX请求中:

$.ajax({
  url: "@Url.Action("PersonExist", "Person")",
  type: "POST",
  dataType: 'json',
  data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
  async: false,
  contentType: "application/json",
  success: function (response) {
      if (response.exists) {
         exists = true;
         getErrorMessage(response.message); //callback
      }
  }

}); });

You can do that with callback functions; 你可以用回调函数来做到这一点;

var personExists = function (callback) {

   var exists = false;
   var errorMsg = null;

    $.ajax({
          url: "@Url.Action("PersonExist", "Person")",
          type: "POST",
          dataType: 'json',
          data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
          async: false,
          contentType: "application/json",
          success: function (response) {
              if (response.exists) {
                 exists = true;
                 errorMsg = response.message;
                 callback(exists, errorMsg);
              }
          }
     });

     if (exists)
       return errorMsg;

     return null;
};

And usage; 和用法;

personExists(function(exists, err) {
    if (exists != null) {
      alert('The person already exists');
      return;
   }    
});

Simply, you can pass exists and errorMsg to callback. 简单地说,您可以将existserrorMsg传递给回调。 See here for further detail on callback functions 有关回调函数的详细信息,请参见此处

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

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