Home Web Front-end JS Tutorial Solve the forward and backward problem of ajax based on Jquery.history

Solve the forward and backward problem of ajax based on Jquery.history

May 24, 2018 pm 03:09 PM
ajax

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>
Copy after login

Username

User id < br/>

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>
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

What are the ajax versions? What are the ajax versions? Nov 22, 2023 pm 02:00 PM

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.

See all articles