如何通过发送GET和POST的javascript重新加载页面,并附加附加参数
How to reload a page with javascript sending both GET and POST, and append additional parameter?
我有一个带有选择框的页面,它会触发onChange事件。在这个Java脚本片段中,我想重新加载当前页面,包括在请求期间发送的GET和POST参数。AFAIK,当不需要发送POST数据时,这可以通过使用window.location.reload()
或window.location.href = window.location.href
来实现。
但是,除了之前发送的元素之外,我还需要附加一个附加值(实际上是select元素的值)。我不在乎数据是使用POST还是GET发送的。有没有办法达到想要的行为?
要实现这一点,您必须从头开始重新构建请求。在get请求的情况下,参数在查询字符串中很容易访问,但post请求有点棘手。你需要将所有的数据隐藏在隐藏的输入元素或其他东西中,这样你就可以访问它
然后你可以试试这样的东西:
var queryString = windlow.location.search; //args from a previous get
var postArgs = $("#myPostArgsForm").serialize(); //args from a previous post... these need to be saved and added to the html by the server
//your additional data... this part you probably need to adapt
//to fit your specific needs. this is an example
var myNewArgName = encodeURIComponent("newArg");
var myNewArgVal = encodeURIComponent("Hello!");
var myNewArgString = myNewArgName + "=" + myNewArgVal;
//if there is no queryString, begin with ?
if(!queryString) {
queryString = "?"
}
//if there is, then we need an & before the next args
else {
myNewArgString = "&" + myNewArgString;
}
//add your new data
queryString += myNewArgString;
//add anything from a previous post
if(postArgs) {
queryString += "&" + postArgs;
}
window.location.href = window.location.hostname + window.location.pathname + querystring
<form id="myPostArgsForm">
<input type="hidden" name="prevQuery" value="whats up?" />
</form>
真的很简单;让onChange激发一个函数,该函数使用getElementById来计算选择器值,然后只使用window.location将浏览器发送到文本:http://yourdomain.com/yourpage.html?selectval=123
然后,在body onload()方法中,激发另一个JS函数,该函数检查"get-var",如:
function (GetSelector) {
var TheSelectorWas = getUrlVars()["selectval"];
alert(TheSelectorWas);
}
并在该函数中执行任何需要执行的操作(document.writes等)。顺便说一句,发布你正在使用的实际代码总是一个好主意。
-Arne
相关文章:
- ROR:如何在不重新加载浏览器的情况下从控制器获取参数
- angularjs-ui路由器父状态,参数加载在子状态之后
- 在页面加载完成之前,使用URL参数运行JavaScript
- 如何在使用javascript加载页面时直接设置对象参数
- React 路由器和任意查询参数:页面在加载时无意中刷新
- 在页面加载时调用函数,在按钮单击时再次调用函数,但参数不同
- 使用Javascript从DB中筛选结果,这将使DIV重新加载它'基于新参数的内容
- 使用参数重新加载父页
- 如何通过发送GET和POST的javascript重新加载页面,并附加附加参数
- 你能写一些javascript,根据URL参数加载两个独立的index.html页面吗
- 如何在事件处理程序中包含函数(及其参数),而不在页面加载时调用该函数
- 如何在没有查询字符串和参数的情况下加载jQuery
- 如何在选择Select Box值时将参数作为POST数据传递,这将重新加载同一页面
- 如何重用 ajax 表单加载函数打开多个选项卡,每个选项卡具有不同的参数
- 我如何让参数“someelement”到图像加载
- 在页面加载时更改 URL 参数
- 为什么函数参数需要这么长时间才能加载
- 使用 vent.js 传递参数.如何在触发事件后加载的下一个页面视图中读取该数据
- 配置模板加载程序以传递额外的参数
- 角度 ui 路由器可选查询参数加载控制器两次