後臺代碼:ajax
[HttpPost] public string DoLogin(string username,string password) { return "success"; }
當使用$.ajax時:json
var name = $('#txtUserName').val(); var pwd = $('#txtPassWord').val(); var param = "{username:'" + name + "',password:'" + pwd + "'}"; $.ajax({ type: "POST", url: "/Main/DoLogin", data: param, contentType: "application/json;charset=utf-8", success: function (msg) { var test = msg; var test2 = test; }, error: function (e) { var test = e; var test2 = test; } });
當使用$.post時:app
var name = $('#txtUserName').val(); var pwd = $('#txtPassWord').val(); var param = { username: name, password: pwd }; $.post('/Main/DoLogin', param, function (result) { var test = result; alert(test); });
區別在於參數的寫法,使用$.ajax時參數要寫成JSON字符串的格式,使用$.post是參數要寫成JSON對象的格式post