search
HomeWeb Front-endJS TutorialSolve the forward and backward problem of ajax based on Jquery.history

This article mainly introduces you to solve the forward and backward problem of ajax based on Jquery.history, which involves the knowledge of jquery forward and backward. The content of this article is classic and has great reference value. I hereby share the knowledge about jquery forward and backward in Script Home Website for your reference

The following content is about Jquery.history solving the forward and backward problem of ajax. Please see below for specific details.

The premise of this article is based on the background, so SEO issues will not be considered here. At the same time, the management system based on the backend does not need to be collected, so it will not consider refreshing situations like directly typing the URL! ! !

The history.state in html5 is used here to solve the problem.

There is already an open source solution for js called pushState on the Internet. See pjax

for details, but this solution is not suitable for my project (backend project), especially the main method is not enough.

I am using jquery.history.js You can refer to this history.js

Look at the code below

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title></title>
  <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
  <script src="js/jquery.history.js"></script>
</head>
<body>

Username

User id

Display results

<p id="ptxtinfo"><input id="txtinfo" type="text"/></p>
<br/>
<a funname="displayinfo" title="wxq" href="javascript:void(0);" class="apjax">提交</a>
<br/>
log:
<textarea id="log" style="width:100%;height:400px"></textarea>
</body>
</html>
<script>
   ///随机数
  function guid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }
 /// 回调的方法
  function doCallback(fn, args) {
    fn.apply(this, args);
  }
    ///获取查询字符串
  function GetQueryString() {
    var result = "";
    var url = location.href;
      if(url.indexOf("?")>0){
        result = url.substring(url.indexOf("?") + 1, url.length);
        if (result != "") {
          result = result + "&";
        }
      }
    return "?" + result;
  }
  // 用来保存地址栏的参数,第一次页面加载的时候执行。 用来修改地址栏的时候,保留原始的参数
  var globalQuerystr;
  var golbalState = {
    "globalPara": {},// js调用方法执行时用的全局js参数,
    "globalControlValue": {},//js需要修改value的html组件 如文本 类似$(“#xxx”).val()
    "globalControlHtml": {},// js需要修改内部html内容的html组件 类似 $(“#yy”).html()
    "CallbackFunctions": "" // 回调的js方法 可以自己实现 ,用逗号分隔,一般是一个方法名
  };
  ///全局变量的问题 globaPara 保存全局变量
  ///多个控件变化 但是不在一个容器内的问题  数组的方式  History.pushState({state:1,rand:Math.random(), "globaPara":globaPara,  "valuecontrol":[{"txtuser":"1"},{"txtname":"2"}]  "htmlcontrol":[{"htmltxt":"<b>hello</b>"},{"htmlcheckbox1":""}] },"title","?data=1"
  //控件类型的问题 有的保存值就行 有的保存html更方便
  (function (window, undefined) {
    globalQuerystr = GetQueryString();
    var
        History = window.History, // Note: We are using a capital H instead of a lower h
        State = History.getState(),
        $log = $(&#39;#log&#39;);
    console.info("页面加载完毕");
    History.log(&#39;initial:&#39;, State.data, State.title, State.url);
    //页面第一次加载的时候 State没有属性
    History.Adapter.bind(window, &#39;statechange&#39;, function () { // Note: We are using statechange instead of popstate
      // Log the State
      var State = History.getState(); // Note: We are using History.getState() instead of event.state
      golbalState = State.data;
      if (golbalState) {
        //修改控件的val值
        if (golbalState.globalControlValue) {
          for (var i = 0; i < golbalState.globalControlValue.length; i++) {
            $("#" + golbalState.globalControlValue[i].controlid).val(golbalState.globalControlValue[i].controlvalue);
          }
        }
        //修改全局变量
        if (golbalState.globalPara) {
          for (var i = 0; i < golbalState.globalPara.length; i++) {
            eval("" + golbalState.globalPara[i].globalname + " =" + golbalState.globalPara[i].globalvalue + ";");
          }
        }
        //修改控件的html
        if (golbalState.globalControlHtml) {
          for (var i = 0; i < golbalState.globalControlHtml.length; i++) {
            $("#" + golbalState.globalControlHtml[i].controlid).html(golbalState.globalControlHtml[i].controlhtml);
          }
        }
        //执行恢复参数后要执行的函数
        if (golbalState.CallbackFunctions != "") {
          doCallback(eval("" + golbalState.CallbackFunctions), null);
        }
        //清空函数
        golbalState.CallbackFunctions = "";
      }
      History.log(&#39;statechange:&#39;, State.data, State.title, State.url);
    });
  })(window);
  function displayinfo() {
    console.info("index:" + History.getCurrentIndex);
     //ajax方法,从服务器获取数据
    $("#txtinfo").val("我爱" + $("#txtUser").val() + $("#txtId").val());
  }
  $(function () {
    $(".apjax").on("click", function () {
      golbalState.globalControlValue = [{"controlid": "txtUser", "controlvalue": $("#txtUser").val()}];
      golbalState.CallbackFunctions = $(this).attr("funname");
      History.pushState(golbalState, $(this).attr("title"), globalQuerystr + "rnd=" + guid());
    });
  })
</script>

First quote the js of jquery and history.js

History.Adapter.bind(window, 'statechange', function () { Indicates that when you click the back forward or history js method, monitor the change. When the change Execute a custom method.

History.pushState has three parameters: state title and custom address query parameters.
This method adds data to the history record and modifies the address bar
History. getState() Get the state parameters of the current address

Three processes

1 First get the parameters of the address bar and save them

2. Bind the click method of the mark containing the apjax class. The mark can be arbitrary, it can be a link button, etc.
When clicked, save the state before executing the ajax method and save it to golbalState. The callback method is from the funname of the mark. Called from the attribute, the value of title is obtained from the title attribute of the mark,
"globalPara": "globalControlValue": "globalControlHtml It is best to assign the value in the ajax method, such as displayinfo

3 History .pushState is added to the history record and the address bar is modified

4 When going back, execute the method in History.Adapter.bind and obtain the state parameter first

5 Modify the variables modified by js before back to the original value, change the value of the previously modified html component back to the original value, and restore the html content in the modified html component to the original value,

6 Re-execute the original executed method, that is, the method saved in CallbackFunctions.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Use postMessage knowledge points in HTML5 to solve POST cross-domain problems in Ajax

##Some about ajax objects Summary of common problems with capitalization of common properties, events and methods

How to solve Ajax request session failure

The above is the detailed content of Solve the forward and backward problem of ajax based on Jquery.history. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Nginx中404页面怎么配置及AJAX请求返回404页面Nginx中404页面怎么配置及AJAX请求返回404页面May 26, 2023 pm 09:47 PM

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

Scrapy基于Ajax异步加载实现方法Scrapy基于Ajax异步加载实现方法Jun 22, 2023 pm 11:09 PM

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

如何使用CakePHP中的AJAX?如何使用CakePHP中的AJAX?Jun 04, 2023 pm 08:01 PM

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

ajax传递中文乱码怎么办ajax传递中文乱码怎么办Nov 15, 2023 am 10:42 AM

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

什么是ajax重构什么是ajax重构Jul 01, 2022 pm 05:12 PM

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

jquery ajax报错403怎么办jquery ajax报错403怎么办Nov 30, 2022 am 10:09 AM

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

使用HTML5文件上传与AJAX和jQuery使用HTML5文件上传与AJAX和jQuerySep 13, 2023 am 10:09 AM

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById(&#39;fileBox&#39;).files[0];varreader=newFileReader();reader.readAsText(file,&#39;UTF-8&#39;);reader.onload=myFunc;functionmyFunc(event){&nbsp;&nbsp;varres

在Laravel中如何通过Ajax请求传递CSRF令牌?在Laravel中如何通过Ajax请求传递CSRF令牌?Sep 10, 2023 pm 03:09 PM

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools