小编典典

jQuery Ajax导致未定义

ajax

我有一个简单的函数,它仅将翻译后的消息从服务器返回到客户端。但是,当我将结果传递给var时,结果显示为未定义。

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

结果- >未定义(错误)

var message = MessageNoResult();
alert(message);

当我查看标题时,它会给我:

Server  ASP.NET Development Server/9.0.0.0
Date    Wed, 09 Nov 2011 09:01:31 GMT
X-AspNet-Version    2.0.50727
Cache-Control   private, max-age=0
Content-Type    application/json; charset=utf-8
Content-Length  24
Connection  Close

Response {"d":"No search result"}
JSON d "No search result"

为什么我仍然得到不确定的结果?


阅读 450

收藏
2020-07-26

共1个答案

小编典典

您可以将回调函数传递给该MessageNoResult函数

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);
    }
  });
}

然后调用:

MessageNoResult(function(msg) {
    alert(msg.d);
});
2020-07-26