你的位置:首页 > ASP.net教程

[ASP.net教程]jquery Ajax异步请求之session


写了一个脚本,如下:

 

 1 $(function () { 2       $("#btnVcode").click(function () { 3         var receiveMobile = $("#Moblie").val();//手机号 4         var regMobile = /^1[3|4|5|7|8][0-9]\d{8}$/;//验证手机 5  6         if (!regMobile.test(receiveMobile)) { 7           helper.dialogError('手机号格式不对'); 8           return; 9         }10         $.post('/Register/SendSms', { Moblie: receiveMobile }, function (jsonObj) {11           helper.checkAjaxStatus(jsonObj, function() {          13           });14         },'json');15       });16     });

 

手机号码验证通过后,会去后台调用发送短信接口,如果短信发送成功,会创建session ,而session的原理有一点是要在客户端浏览器创建cookie用来存ASP.NET_SessionId.

刚写完这段代码时担心Ajax异步请求不会创建本地cookie存sessionId.  ~.~

因为后台返回的是一个Json字符串: {"status":0,"msg":"短信已发送,请注意查收!"}

纠结了一会,想怎么解决.

 

试试再说,经测试,竟然创建cookie了.(后台没有操作cookie,返回的结果是字符串,也没有用jquery去操作去生成cookie,然而,然而,却有了...有了...)

查看报文-->

POST http://localhost:1813/Register/SendSms HTTP/1.1
Host: localhost:1813
Connection: keep-alive
Content-Length: 18
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:1813
X-Requested-With:
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:1813/Register/EpUser
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8

Moblie=***********

 

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Set-Cookie: ASP.NET_SessionId=zbdy1ndgta2g02lysrfv1rhj; path=/; HttpOnly
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?ZDpcYmFja3VwXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTNcUHJvamVjdHNcTFNVbmlvblxMU1VuaW9uLlNpdGVcUmVnaXN0ZXJcU2VuZFNtcw==?=
X-Powered-By: ASP.NET
Date: Fri, 29 Jan 2016 11:03:17 GMT
Content-Length: 53

{"status":0,"msg":"短信已发送,请注意查收!"}

 

真的有了.据分析,应该是 

  Session[Keys.smsVcode] = vcode;//短信发送成功才创建session 

这行代码会 自动创建一个cookie并放入响应流(类似 Response.Cookies.Add(...) ),体现在报文的头部,浏览器收到报文,根据

   Set-Cookie: ASP.NET_SessionId=zbdy1ndgta2g02lysrfv1rhj; path=/; HttpOnly

创建了cookie.

 

分析完毕.