如何通过发送GET和POST的javascript重新加载页面,并附加附加参数

How to reload a page with javascript sending both GET and POST, and append additional parameter?

本文关键字:加载 参数 新加载 GET 何通过 POST javascript      更新时间:2024-04-24

我有一个带有选择框的页面,它会触发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