【问题标题】:How do I change the address bar when I make an Ajax request?发出 Ajax 请求时如何更改地址栏?
【发布时间】:2012-12-08 04:32:06
【问题描述】:

我创建了一个网站,该网站大量使用 Ajax 来加载其内容。 我希望我选择的页面加载到 AJAX 上,但同时 URL 也会更改,而无需重新加载整个页面内容。我将如何实现这一目标?我已经用谷歌搜索了,但我的搜索没有产生任何结果。

假设我有这个页面:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <sj:head />
</head>
<body>
    <h5>Struts Jquery Ajax Integration </h5>

    <div id="resultContent"></div>
    <noscript>Please Turn On Javascript to make the full use of this site</noscript>

    <h4>Choose A task</h4>
    <ul>
        <s:url value="views/ajaxvalidation.jsp" var="ajaxvalidation" />
        <li><sj:a targets="resultContent" href="%{ajaxvalidation}">Ajax Validation </sj:a></li>
    </ul>

    <div>
        <h6>Play A Music while You Navigate</h6>
        <audio src="x.mp3" controls>Your browser does not support the
            audio element.
        </audio>
    </div>
</body>
</html>

我单击了 Ajax 验证链接。它不会重新加载页面,但是 url 会是这样的:

localhost:8090/AppName/ajaxvalidation.jsp

或者这个:

 localhost:8090/AppName/ajaxvalidation.action

我将如何实现这样的目标?

请注意,我正在使用这个插件:struts2-jquery

【问题讨论】:

  • 似乎您必须在处理 ajax 响应的处理程序代码上使用一些 javascript。我认为在 struts 方面没有任何东西可以实现这一点,如果这就是你的想法的话。 . .
  • 我已经更新了我的问题。
  • 我认为这是不可能的;使用ajax意味着您将页面的片段发送到服务器,更改url意味着更改操作
  • R U说你想在Ajax调用时更改浏览器地址栏中的URL?
  • @chad 是的,这正是我想要发生的事情。

标签: java jquery ajax url-rewriting struts2


【解决方案1】:

您需要使用History API

window.history.pushState(data, title, url)

更新

注意到您使用了struts2-jquery,您可以添加ajaxhistory="true" 以启用在ajax 历史记录功能中的构建。见http://code.google.com/p/struts2-jquery/wiki/HeadTag#Attributes

<sj:head ajaxhistory="true" />

但请记住,并非所有浏览器版本都支持它..

【讨论】:

  • 你能举个例子吗?只是 sn-p 没有多大意义。
  • 假设我已经设置了 ajaxhistory ="true" 那么我将如何将它与 window.history.pushState 一起使用?我开始明白这个想法,但仍然没有关于实施的线索。还是我只使用上述标签?
  • @KyelJmD 是的,忽略pushState。我相信struts2 库会在内部处理这个问题..
  • 我注意到的一件事,我似乎无法自定义正在生成的 url,有什么解决方案吗?它正在生成一个类似于 #resultContent=_sj_action_ajaxvalidationresultContent 的 url。我想删除 sj_action。价值
  • @KyelJmD,对 struts2 不够了解,所以我无法提供帮助.. 也无法集成 pushState,因为 ajax 调用由 struts2 框架在内部处理..
【解决方案2】:

如果浏览器支持(read < IE10),您可以使用history.pushState

var boolPushState  = false;
if (typeof history.pushState !== "undefined") {
        boolPushState = true;
}

if (boolPushState) {
    history.pushState(null, null, "URL");
}

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 2023-03-03
    • 2018-07-04
    • 2014-03-20
    • 1970-01-01
    • 2019-07-12
    • 2021-08-06
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多