JS获取Ip和浏览器信息,用户逗留时间写进数据库

NeptuneSafari 2013-08-15

Default.aspx

<script src="jquery.js" type="text/javascript"></script>
     <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>  
    <script src="JS.js"></script>

JS.js

var fromURL;
var IP = returnCitySN["cip"];
var city = returnCitySN["cname"];
var Browse;

window.onload = function () {

    fromURL = window.document.referrer;
    if (fromURL == "") {
        fromURL = "NOFromSource";
    }
}

var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
/*以下进行测试*/
if (Sys.ie) Browse = 'IE: ' + Sys.ie;
if (Sys.firefox) Browse = 'Firefox: ' + Sys.firefox;
if (Sys.chrome) Browse = 'Chrome: ' + Sys.chrome;
if (Sys.opera) Browse = 'Opera: ' + Sys.opera;
if (Sys.safari) Browse = 'Safari: ' + Sys.safari;
if (Sys.ie == 6.0) { Browse = 'IE: ' + Sys.ie }


var start = new Date();

var time;
window.onbeforeunload = function () {
    var end = new Date();
    time = end.getTime() - start.getTime();
    time = time / 1000;
    $(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "WebService.asmx/Receive",
            data: "{IP:'" + IP + "',city:'" + city + "',fromURL:'" + fromURL + "',Browse:'" + Browse + "',time:'" + time + "'}",
            dataType: 'json',
            success: function (result) {
             //window.document.write(result.d);
            }
        });
    });

    return ;
};

web.config

<add name="Table" connectionString="Data Source=HUGO-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
    </connectionStrings>

webService.cs

[WebMethod]  
    public void Receive(string IP, string city, string fromURL, string Browse, string time)
    {
        
        string connStr = ConfigurationManager.ConnectionStrings["Table"].ConnectionString;
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "insert into ssk(time) values('456')";
        cmd.ExecuteNonQuery();
        conn.Close();

        //return "456";
    }

相关推荐