解决ajax异步传输数据,return返回为undefined的问题
- 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;
- }
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,即修改此方法为同步
- function GetUserInfo(tp) {
- var username;
- $.ajax({
- type: "POST",
- cache: false,
- data: "type=exlogin&tp=" + tp,
- async: false,
- url: "Handle/OpeartionHandler.ashx",
- success: function(userinfo) {
- username = userinfo;
- }, error: function(data) {
- username = "";
- }
- });
- return username;
- }