如何通过仅使用 jQuery 构建的单页应用程序实现路由 [英] How to implement routing with a single page application build solely using jQuery

查看:37
本文介绍了如何通过仅使用 jQuery 构建的单页应用程序实现路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,当用户在文本字段中输入一个词并点击搜索时,表单使用 $.get() 提交.从服务器获取数据(JSON),然后更新 UI.

Right now when the user inputs a word in the textfield and hits search, the form submits using $.get(). The data(JSON) is fetched from the server and then the UI is updated.

我想做的很简单:

1) 当表单提交时,浏览器的 URL 需要更新(类似于 search/zyxzyx 就是用户搜索的内容).

1) When the form submits, the URL of the browser needs to update (something like search/zyx, zyx is what the user is searching for).

2) 当页面被预订到收藏夹时,或者作为链接从页面需要加载的某个地方单击时,文本字段值必须是zyx".此外,UI 需要显示 zyx 的搜索结果.

2) when the page is booked into favorites, or clicked as a link from somewhere the page needs to load and then the textfield value have to be 'zyx'. Also the UI needs to show search result of zyx.

这对我的应用很重要,因为我将使用 Google Analytics.所以需要 URL 来反映行为.加上其他问题,如后退按钮历史记录.这是否可以仅使用 jQuery 或一些基于 jQuery 构建的极其轻量级的库.我到处搜索,我找到的所有解决方案都使用 MVC 框架.或者另一种解决方案是使用像这个这样的模板框架.然而,我的应用对于这些解决方案来说太简单了.

This is important to my app because I will be using Google Analytics. So the URL is needed to reflect behaviour. Plus the other issue like back button history. Is this possible using just jQuery or some extremely light libraries build on jQuery. I have searched everywhere and all the solutions I found were using MVC frameworks. Or another solution was to use a templating framework like this one. However my app is way too simple for these solutions.

推荐答案

因此,您需要的方法是监听 url 中的哈希更改,并基于此获取当前页面并将其呈现在 cointainer 中.像这样:

So, the approach you you need is to listen to hash changes in the url and based on this get the current page and render it in a cointainer. Something like this:

<a href="#page2">Go to Page 2</a>
<div class="page-container"></div>
<script>
$(window).on('hashchange',function(){ 
  var page = window.location.hash;
  $.get('pages/'+page+'.html', function(pageContent){
     $('.page-container').html(pageContent);
  })   
});
</script>

这篇关于如何通过仅使用 jQuery 构建的单页应用程序实现路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆