jQuery Ajax results in undefined

白昼怎懂夜的黑 提交于 2019-11-29 05:21:27

You can pass a callback function to the MessageNoResult function

function MessageNoResult(callback) {
  $.ajax(
  {
    type: "POST",
    async: true,
    url: '<%= ResolveUrl("~/WebMethods.aspx/MessageNoResult") %>',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      callback(msg);
    }
  });
}

And then call:

MessageNoResult(function(msg) {
    alert(msg.d);
});

The ajax call is still being executed as your code moves on to the alert(message) line, so the message variable has no value.

You need to pass the value of the response to a function within the success method.

success: function(msg) {
  myFunction(msg.d);
}

// outside ajax call
function myFunction(ajaxValue) {
    alert(ajaxValue)
}

The ajax call is an async call and you’re running the alert right after the MessageNoResult, thus the message has no value until you’ve actually completed the ajax request.

You’ll need to run your alert inside the success from ajax call.

You are trying to return from success which is a callback function. Set a global variable and use it within the success function retmess = msg.d to store the return or set the content of an html element jQuery('#status').html(msg);

njr101

Your code:

var message = MessageNoResult();

is setting the message variable to the return value of the MessageNoResult functiion. Since you have no return value in this function, you get undefined as response.

The corrcet way to handle this is by dealing with the return value from the Ajax call inside the success callback.

For a similar question see my answer here:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!