解决ajax异步传输数据,return返回为undefined的问题

  1. function GetUserInfo(tp) {
  2. var username;
  3. $.ajax({
  4. type: "POST",
  5. cache: false,
  6. data: "type=exlogin&tp=" + tp,
  7. url: "Handle/OpeartionHandler.ashx",
  8. success: function(userinfo) {
  9. username = userinfo;
  10. }, error: function(data) {
  11. username = "";
  12. }
  13. });
  14. return username;
  15. }
function GetUserInfo(tp) {
var username;
$.ajax({
type: "POST",
cache: false,
data: "type=exlogin&tp=" + tp,
url: "Handle/OpeartionHandler.ashx",
success: function(userinfo) {
username = userinfo;
}, error: function(data) {
username = "";
}
});
return username;
}

对于此方法调用之后会一直返回undefined,原因是Jquery的ajax是异步的,所以大多时候没执行完AJAX就return htmlcontent了,所以会一直返回undefined,

解决方法:添加async: false,即修改此方法为同步

  1. function GetUserInfo(tp) {
  2. var username;
  3. $.ajax({
  4. type: "POST",
  5. cache: false,
  6. data: "type=exlogin&tp=" + tp,
  7. async: false,
  8. url: "Handle/OpeartionHandler.ashx",
  9. success: function(userinfo) {
  10. username = userinfo;
  11. }, error: function(data) {
  12. username = "";
  13. }
  14. });
  15. return username;
  16. }
上一篇:keepalived+mysql双主复制高可用方案


下一篇:CLR 公共语言运行库