每半秒刷新页面5次,然后使用javascript或JQuery将查询字符串附加到url

时间:2014-10-02 09:35:09

标签: javascript jquery

我需要编写一些刷新页面的JavaScript或jQuery,每5秒刷新一次,然后一旦完成,使用javascript或JQuery将一个查询字符串变量(?refreshed = yes)附加到url。

目前我只能在0.5秒后刷新一次并附加?refreshed = yes querystring。有人可以指出我正确的方向,非常感谢任何回复。

 <script>
    window.onload = function () {
        if (!window.location.search) {
            setTimeout("window.location+='?refreshed=yes';", 500);
        }
    }
</script>

C#代码 -

using LinkChex.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;

namespace LinkChex.Base
{
    public class WebSpider
    {

        const int LIMIT = 10;
        string[] invalidTypes = { ".zip", ".doc", ".css", ".pdf", ".xls", ".txt", ".js", ".ico" };

        public List<LinkModels> Links;
        public bool foundMatch = false;

        public bool IsRunning { get; set; }
        public bool IsDone { get; set; }
        public int totLinks { get; set; }
        public WebSpider()
        {
            this.Links = new List<LinkModels>();
        }
        public void Execute(string url)
        {

            this.Links.Clear();
            this.Links.Add(new LinkModels() { Status = HttpStatusCode.OK, NavigateUrl = url });

            this.IsRunning = true;
            WaitCallback item = delegate(object state) { this.FindLinks((UrlState)state); };
            ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = url, Level = 0 });
            this.totLinks = Links.Count(); 
        }
        public void FindLinks(UrlState state)
        {
            try
            {
                string html = new WebClient().DownloadString(state.Url);
                MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
                foreach (Match match in matches)
                {
                    string value = match.Value;
                    value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
                    if (value.EndsWith("\"") || value.EndsWith("'"))
                        value = value.Remove(value.Length - 1, 1);
                    if (!Regex.Match(value, @"\((.*)\)").Success)
                    {
                        if (!value.Contains("http:"))
                        {
                            Uri baseUri = new Uri(state.Url);
                            Uri absoluteUri = new Uri(baseUri, value);
                            value = absoluteUri.ToString();
                        }
                        if (this.Links.Exists(x => x.NavigateUrl.Equals(value))) continue;
                        try
                        {
                            bool validLink = true;
                            foreach (string invalidType in invalidTypes)
                            {
                                string v = value.ToLower();
                                if (v.EndsWith(invalidType) || v.Contains(string.Format("{0}?", invalidType)))
                                {
                                    validLink = false;
                                    break;
                                }
                            }
                            if (validLink)
                            {
                                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
                                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                                //add the OK link to the List object
                                //COMMENTED TO FILTER OUT OK LINKS
                              //  this.Links.Add(new LinkModels() { Status = response.StatusCode, NavigateUrl = value });
                                if (response.StatusCode == HttpStatusCode.OK && state.Level < LIMIT)
                                {
                                    WaitCallback item = delegate(object s) { FindLinks((UrlState)s); };
                                    ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = value, Level = state.Level + 1 });


                                }
                            }
                        }
                        catch 
                        {
                            //add the ExpectationFailed link/s to the List object

                            this.Links.Add(new LinkModels(){ Status = HttpStatusCode.ExpectationFailed, NavigateUrl = value});
                           // this.IsDone = true;
                        }




                    }

                }
            }
            catch
            {
                ///
                /// If downloading times out, just ignore...
                /// 
            }
        }
    }
}

控制器类 -

  public WebSpider WebSpider
        {
            get { return (WebSpider)(Session["webSpider"] ?? (Session["webSpider"] = new WebSpider())); }
        }

 [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public ActionResult Details(string refreshed, int id = 0)
        {

            LinkModels lm = new LinkModels();
            Domain domain = db.Domains.Find(id);

            if (domain == null)
            {
                return HttpNotFound();
            }
            else
            {

            if (!this.WebSpider.IsRunning)
            {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(domain.DomainDesc);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode == HttpStatusCode.OK)
                    this.WebSpider.Execute(domain.DomainDesc);
            }
            if (!this.WebSpider.IsRunning)
            {
                lm.SpiderRunning = this.WebSpider.IsRunning;

            }

            }
            //remove duplicates from list object
            var distinctList = this.WebSpider.Links.GroupBy(x => x.NavigateUrl)
                                                   .Select(g => g.First())
                                                   .ToList();

            //only send email if page has been refreshed, NOT on initial load
            if (Request["refreshed"] == "yes")
            {
                SendCertificate(domain.UserProfiles.UserName, domain.UserProfiles.UserEmail, domain.DomainDesc, distinctList);
            }

            return View(distinctList);
        }

2 个答案:

答案 0 :(得分:2)

在查询字符串中再添加一个参数,如refresh=X,并在函数中解析此参数。

另一个选项是使用本地存储来存储这些数据。

答案 1 :(得分:1)

您可以尝试以下内容:

var l = document.location, 
    m = l.search.match(/counter=(\d+)/),
    counter = parseInt(m&&m[1]) || 0;
if (counter<5)
   setTimeout(function() {
       l.href = l.origin+l.pathname+"?counter="+(++counter);
   },500);