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

标签 javascript jquery

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

目前我只能在 0.5 秒后刷新一次并附加 ?refreshed=yes 查询字符串。有人可以指出我正确的方向吗,非常感谢您的回复。

 <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...
                /// 
            }
        }
    }
}

Controller 类 -

  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);
        }

最佳答案

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

另一个选项是例如使用本地存储来存储此数据。

关于javascript - 每半秒刷新页面 5 次,然后使用 javascript 或 JQuery 将查询字符串附加到 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158080/

相关文章:

javascript - 你如何配置nowjs?

javascript - 使用 jQuery 将一个字段的内容复制到另一个字段

javascript - 以编程方式搜索图像

javascript - jQuery 切换在 IE 中不起作用

javascript - 删除 ngFor 中的前 4 个字符

javascript - google api不适用于地理定位

javascript - 隐藏所有站点页面上的元素

javascript - jquery简单交换p元素?

javascript - HighCharts 导出隐藏滚动条

javascript - 带有脚本标签的jquery find() 和remove() 不起作用