我正在从事一个业余爱好项目(通常是一名设计师,所以对 php 不太熟悉 - 请监督所有或任何冗余代码),尝试学习新东西。现在我遇到了一个我似乎不太掌握窍门的问题。 我有一个 index.php 用于显示 data.php 中的随机句子,这工作得很好 - 但是我希望能够在必要时为不同的人整理出特定类型的句子。这是通过包含设计师、插画家和开发人员的下拉列表完成的。
例如,如果您从下拉菜单中选择“开发人员”,页面将重新加载,并在 URL 中显示 index.php?yrke=developer
。这一切都很好并且符合预期,当我从 data.php 回显 $_GET['yrke'];
时,它会在第一次加载时显示文本“developer”,但是单击 randomizerButton
按钮(注意内容是从 data.php 加载的,点击此按钮时不会刷新浏览器中的页面) $_GET['yrke'];
似乎不能读取 url 中的值(将 $_GET['yrke'];
放在 index.php
中显然是可行的,但我需要访问 url 变量在 data.php 中)。
如果有办法做到这一点,同时保持“update-content-without-browser-refresh”功能那就太棒了,另一个最简单的解决方案可能是删除所说的“update-content-without-browser-refresh”刷新”并进行良好的旧刷新,从而解决问题 - 但是为什么要让它那么简单,对吧?
index.php (摘录)
<button data-href="data.php" class="randomizerButton">Randomize sentences</button>
<form action="index.php" method="get">
<select name="yrke" onchange="this.form.submit()">
<option value="designer"<?=$_GET['yrke'] == 'designer' ? ' selected="selected"' : '';?>>Designer</option>
<option value="illustrator"<?=$_GET['yrke'] == 'illustrator' ? ' selected="selected"' : '';?>>Illustrator</option>
<option value="developer"<?=$_GET['yrke'] == 'developer' ? ' selected="selected"' : '';?>>Developer</option>
</select>
</form>
<?php include('data.php'); ?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
data.php (摘录)
echo $_GET['yrke'];
最佳答案
如果您想在 data.php
上使用 $_GET['yrke']
您必须使用 $.get()
并且只需使用完整的 URL,例如:
$.get('data.php?yrke='+encodeURIComponent($('[name=yrke]').val()), function(response){
$('#results').html(response);
}
我会用
$.post('data.php', {yrke:encodeURIComponent($('[name=yrke]').val())}, function(response){
$('#results').html(response);
}
在 data.php
上使用 $_POST['yrke']
。通常,我不会有以传统方式提交的表单。这都是关于 AJAX 的。
关于javascript - 重新加载时从 url 获取 php 变量而不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454238/