以這個典型例子:
$("InputButton").click(function () { $.ajax({ type: "POST", url: "webservice/DataService.asmx/GetAccount", data: "{AccountNo: '123' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg){ alert(msg); } }); });
上面的例子是沒有問題的,但如果把Ajax部份寫成Function,就會出現CallBack空白的Data:
$("InputButton").click(function () { alert(GetAccountName('123')); }); function GetAccountName(Code) { var r = ''; $.ajax({ type: "POST", url: "webservice/DataService.asmx/GetAccount", data: "{AccountNo: '" + Code +"' }", contentType: "application/json; charset=utf-8", dataType: "json", //async: false, //假設沒有這行 success: function(msg){ if (msg.length > 0) { r = msg; } } }); return r; }
解決的方法就是加入這一行
async: false,
用意是需要等待jQuery 取得Data後才運行下一個動作。
你都用 ASP.NET + jQuery 頂 ASP.NET AJAX 呀,同道中人喎,
回覆刪除不過我都未攪得掂晒 jqGrid ,你有無用過 d 好既 jQuery Grid 係夾 ASP.NET 係正既?
我個朋友開左個 forum ,唔知你有無興趣望下 http://programmers.hk/forum/index.php
[...] 之前已經略略打過一篇jQuery 的Async和sync的問題: jQuery – Why Ajax return blank data? [...]
回覆刪除我本來用$.ajax() + data.d冇問題
回覆刪除但我今日用$.post()代替$.ajax(),個data裡面.d就唔見左!
你知唔知係咩問題?
其實$.post()只係$.ajax() Type:'Post'既簡寫,所以data唔見晒的話,我覺得應該同轉用$post冇關係,不如你試下用firebug或者IE Developer Toolbar去試下Debug.
回覆刪除[...] This post was mentioned on Twitter by onion_soup. onion_soup said: http://tinyurl.com/2g35rqp jQuery – Why Ajax return blank data? | 亞特蘭提斯(BLOG.MIAWORK.COM) [...]
回覆刪除