无需重新加载即可更改页面的好习惯

时间:2018-12-11 16:53:20

标签: javascript ajax

我正在尝试更改页面,但没有重新加载 这是我的工作: AJAX:

 app.ajax.client.request = function(headers, path, method, queryObj, payload, cb) {
    // Set defaults
    headers = typeof(headers) == 'object' && headers !== null ? headers : {};
    path = typeof(path) == 'string' ? path : '/';
    method = typeof(method) == 'string' && ['POST','PUT','DELETE','GET'].indexOf(method.toUpperCase()) > -1 ? method.toUpperCase() : 'GET';
    queryObj = typeof(queryObj) == 'object' && queryObj !== null ? queryObj : {};
    payload = typeof(payload) == 'object' && payload !== null ? payload : {};
    cb = typeof(cb) == 'function' ? cb : false;
    // For each query string parameter sent, add it to the path
    let requestUrl = path + '?';
    let counter = 0;
    // Set the request url based on the query object
    for (let i in queryObj) {
      if (queryObj.hasOwnProperty(i)) {
        counter++
        if (counter > 1) {
          requestUrl += '&';
        }
        requestUrl += i + '=' + queryObj[i];
      }
    }
    // Form the http request as a JSON type
    let xhr = new XMLHttpRequest();

    xhr.open(method, requestUrl, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    // For each header sent, add it to the request
    for (let i in headers) {
      if (headers.hasOwnProperty(i)) {
        xhr.setRequestHeader(i, headers[i]);
      }
    }

    // When the request comes back, handle the response
    xhr.onreadystatechange = function() {
      // Set the parameters that will be called back
      let readyState = xhr.readyState;
      let statusCode = xhr.status;
      let responseReturned = xhr.responseText;
      // Parse the response
      let parsedResponse = app.isJsonString(responseReturned);

      if (parsedResponse) { // If the response text is a JSON, callback parsedResponse, if not, callback the not parsed response instead
        cb(readyState, statusCode, parsedResponse);
      } else {
        cb(readyState, statusCode, responseReturned);
      }
    }
    // Send the payload as JSON
    let payloadString = JSON.stringify(payload);
    xhr.send(payloadString);
}

客户请求:

app.changeToIndexPage = function(e) {
 e.preventDefault();
 if (!app.mainContainer.hasClass('index')) { 
  app.closePage(); // show a loading screen
  history.pushState({}, '', '/'); //Set the url to the index's url
  setTimeout(function() {
    app.ajax.client.request(undefined, 'public/request/index.txt', 'GET', undefined, undefined, function(readyState, statusCode, response) { // Get the request
      console.log(readyState);
      if (readyState < 3) { 
        app.preloader.addClass('loading');
      } else if (readyState == 4 && statusCode == 200) {
        app.navContainer.attr('class', app.navContainer.attr('class').replace(/index|project|about|contact/g, 'index'));
        setTimeout(function() {
          app.mainContainer.html(response);
        }, 500);
      }
    });
  }, 100);
}

}

因此,例如: 如果我不在索引页面上,但想转到索引页面,则可以运行changeToIndexPage函数,而ajax将请求所需的文件,并根据所需的操作更改html元素。我唯一的问题是,有没有更好的解决方案?

1 个答案:

答案 0 :(得分:1)

如果要采用AJAX提取页面并将其打入文档的方法(我一开始不建议这样做),则应该具有通用功能。

该函数应具有function navigate(path) { ... }之类的签名。它应该添加历史记录条目,获取适当的文档并将其插入页面。

然后,您需要附加一个事件侦听器以捕获popState个事件,因此,当用户按下后退按钮时,您将从弹出的历史记录条目中检索路径并将其传递给{{1} }。

同样,如果您要构建SPA,我不建议您像这样构建它。 SPA的主要优点之一是在客户端上呈现文档所带来的性能提升,而这种方法无法利用。考虑使用基于组件的客户端渲染库,如React或Angular。