我的头文件中有一个下拉元素。该下拉列表包含2种货币,我希望我的网站上的用户可以选择:
<div class = "currencyswitcher">
<span class = "currencylabel"><strong>Currency Switcher</strong> </span>
<form method="post" id="switchcurrency" name = "switchcurrency">
<select name = "currency" id = "currency" >
<option value = "USD"> USD </option>
<option value = "KES"> KES </option>
</select>
</form>
</div>
这是由ajax脚本处理的,该脚本将所选元素发布到另一个文件:
<script>
$(document).ready(function() {
var url = "<?php echo file2.php;?>";
$('#currency').change( function() {
$.ajax({
data: $('#switchcurrency').serialize(),
type: "POST",
url: url,
success: function(response) {
alert(response);
}
});
});
});
</script>
现在,在我的file2.php中,我想从我的下拉列表中传递值并将其附加到我正在访问的页面的url,即如果我在页面上的sitename.php / page1然后从中选择下拉,页面刷新到sitename.php / page1?currency = USD,如果我在sitename.php / page2,选择后,页面刷新到sitename.php / page2?currency = KES等等......
这是我的file2.php(ajax发布到的文件)
if(isset($_POST["currency"]))
{
$key = key($_POST);
$value = $_POST["currency"];
$params = array_merge($_GET, array($key => $value));
$new_query_string = http_build_query($params);
$url = (empty($_SERVER['HTTPS'])?"http://":"https://") . $_SERVER['REQUEST_URI'] . "?" . $new_query_string;
var_dump($url);
}
从上面我的转储返回我的标题页的网址,即
var_dump($url); = mysiteurl/header.php?currency=USD
所以这是我的问题:通过我在标题中的下拉列表(因此调用我网站中的所有页面),我如何强制执行它,以便在选择一个选项时,我正在使用所选选项刷新当前页面附加到网址?
答案 0 :(得分:0)
试试这个
<script>
$(document).ready(function() {
var url = "<?php echo file2.php;?>";
$('#currency').change( function() {
$.ajax({
data: $('#switchcurrency').serialize(),
type: "POST",
url: url,
success: function(response) {
//Choose one!!
// similar behavior as an HTTP redirect
window.location.replace(response);
// similar behavior as clicking on a link
window.location.href = response;
}
});
});
});
</script>
if(isset($_POST["currency"]))
{
$key = key($_POST);
$value = $_POST["currency"];
$params = array_merge($_GET, array($key => $value));
$new_query_string = http_build_query($params);
$url = (empty($_SERVER['HTTPS'])?"http://":"https://") . $_SERVER['REQUEST_URI'] . "?" . $new_query_string;
exit($url);
}
答案 1 :(得分:0)
使用ajax中的.done
回调来处理更改window.location.href
属性(您可以添加货币参数键/值对):
$(document).ready(function() {
var url = "<?php echo file2.php;?>";
$('#currency').change( function() {
$.ajax({
data: $('#currency').serialize(),
type: "POST",
url: url,
success: function(response) {
alert(response);
}
}).done(function() {
window.location.href = window.location.href + "?currency="+$('#switchcurrency').val();
});;
});
});
进一步阅读:
http://api.jquery.com/jquery.ajax/
https://developer.mozilla.org/en-US/docs/Web/API/Window/location