I need to work 开发者_StackOverflow社区with an ajax powered web page so I can pass an id or ids in the URL and it'll only display result(s) based on the id(ids) passed in. For an old cgi page, I could do: http://myurl?id=1, is there a way of doing this for Ajax pages? Thanks,
David
Simplest - use anchors and the hashchange
event to modify the state of the URL (you'll mostly need a shiv for older browsers like IE 6 and 7). When the page first loads, parse the hash and load what you need to via ajax. (An example of library to help with that Ben Alman's jQuery bbq
plugin.) Your URLs in this case will look like this:
http://example.com/entry/point#/my/app%3Fq=1
Neater - use the new history
API to pushState
as the page changes for newer browsers and fallback on hashchange
for browsers that don't support the new HTML5 goodness. (An example of a library that helps with that is Ben Lupton's History.js plugin). Your URLs for newer browsers will look like this:
http://example.com/my/app?q=1
while URLs for browsers that don't support the new API will see the hashchange
URL.
Neatest - use a full routing or MVC framework and don't re-invent the wheel. Examples include, but are not limited to:
- JavascriptMVC
- Backbone.js
- Spine.js
- Crossroads.js
Note that with the newer history
API, you really should make sure that all of your URLs are actually reachable and usable without JavaScript. (So if you push http://example.com/my/app?q=1
onto the history stack you should be able to type that URL into your browser's address bar and just go there.)
Sure, make your XmlHttpRequest with a get request and add your parameter on the url string, the same way you would have done it if calling the page. You need to "craft" your url using javascript.
If using jQuery you could just use the $.get() method.
If using native DOM methods you would need to create an XMLHttpRequest with the appropriate url and callback.
If you can use JSP, this will work...
<body onload='initViaAjax();'>
<div id='insertHTML'></div>
<input id='passedID' type='hidden' value='<%=request.getParameter("id")%>'/>
The getParameter will populate with your query string id value. The onload event can access that value and use it in your ajax call. The ajax result can be pushed into the div tag.
精彩评论