如何使用JavaScript在页面加载时获取get或post变量的值?
如何使用JavaScript在页面加载时获取get或post变量的值?
你不能使用JavaScript获取POST变量的值,尽管在服务器处理请求时可以将其插入文档中。
<script type="text/javascript">
window.some_variable = '<?=$_POST['some_value']?>'; // That's for a string
</script>
通过 window.location.href
可以获取 GET 变量,而一些框架甚至有已准备好的 方法 可以解析它们。
json_encode
来代替直接编写POST值。 - Ken Keenan只有使用JavaScript才能获取URI参数。
// get query arguments
var $_GET = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
<input id="input_id" type="checkbox/text/radio" value="mehrad" />
<div id="writeSomething"></div>
function checkvalue(input , Write) {
var inputValue = document.getElementById(input).value;
if(inputValue !="" && inputValue !=null) {
document.getElementById(Write).innerHTML = inputValue;
} else {
document.getElementById(Write).innerHTML = "Value is empty";
}
}
此外,您可以在此功能中使用其他代码或其他if语句,如下所示:
function checkvalue(input , Write) {
var inputValue = document.getElementById(input).value;
if(inputValue !="" && inputValue !=null) {
document.getElementById(Write).innerHTML = inputValue;
document.getElementById(Write).style.color = "#000";
} else {
document.getElementById(Write).innerHTML = "Value is empty";
}
}
你可以通过类似以下事件在你的页面中使用该函数:
<div onclick="checkvalue('input_id','writeSomthing')"></div>
<Mehrad Karampour>
最简单的技巧:
如果您省略了表单操作属性,只需在用于提交表单的按钮上使用 onClick,就可以将表单发送到同一HTML文件,而无需实际使用GET HTTP访问。然后,表单字段位于元素数组document.FormName.elements中。该数组中的每个元素都有一个value属性,其中包含用户提供的字符串(对于INPUT元素)。它还具有id和name属性,其中包含表单子元素中提供的id和/或name。
这是我对于给定一个字符串returnURL的答案,该字符串类似于http://host.com/?param1=abc¶m2=cde。由于我刚刚开始学习JavaScript(这实际上是我在JS中的第一个程序的一部分),所以它相当基础,并且更加易于理解而不是复杂。
备注
这仅适用于GET,而不是POST
var paramindex = returnURL.indexOf('?');
if (paramindex > 0) {
var paramstring = returnURL.split('?')[1];
while (paramindex > 0) {
paramindex = paramstring.indexOf('=');
if (paramindex > 0) {
var parkey = paramstring.substr(0,paramindex);
console.log(parkey)
paramstring = paramstring.substr(paramindex+1) // +1 to strip out the =
}
paramindex = paramstring.indexOf('&');
if (paramindex > 0) {
var parvalue = paramstring.substr(0,paramindex);
console.log(parvalue)
paramstring = paramstring.substr(paramindex+1) // +1 to strip out the &
} else { // we're at the end of the URL
var parvalue = paramstring
console.log(parvalue)
break;
}
}
}
// Captura datos usando metodo GET en la url colocar index.html?hola=chao
const $_GET = {};
const args = location.search.substr(1).split(/&/);
for (let i=0; i<args.length; ++i) {
const tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
console.log(`>>${$_GET['hola']}`);
}//::END if
}//::END for
当我遇到这个问题时,我将该值保存到了一个隐藏的输入框中:
在 HTML 主体中:
<body>
<?php
if (isset($_POST['Id'])){
$fid= $_POST['Id'];
}
?>
...然后将隐藏的输入放在页面上,并使用PHP echo写入值$fid
<input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">
然后在 $(document).ready( function () {
var postId=document.getElementById("fid").value;
所以我在 PHP 和 JS 中获取了我的隐藏 URL 参数。
"
并打破属性)。 - Mark Fowler使用少量的 PHP 非常容易。
HTML 部分:
<input type="text" name="some_name">
JavaScript
<script type="text/javascript">
some_variable = "<?php echo $_POST['some_name']?>";
</script>
"
的内容,那么他们可以跟随任意JavaScript。 - Mark Fowler"
是不够的,还需注意防范 </script>
。建议使用 json_encode
(现在转义反斜线) - Mark Fowler/**
* getGET: [Funcion que captura las variables pasados por GET]
* @Implementacion [pagina.html?id=10&pos=3]
* @param {[const ]} loc [capturamos la url]
* @return {[array]} get [Devuelve un array de clave=>valor]
*/
const getGET = () => {
const loc = document.location.href;
// si existe el interrogante
if(loc.indexOf('?')>0){
// cogemos la parte de la url que hay despues del interrogante
const getString = loc.split('?')[1];
// obtenemos un array con cada clave=valor
const GET = getString.split('&');
const get = {};
// recorremos todo el array de valores
for(let i = 0, l = GET.length; i < l; i++){
const tmp = GET[i].split('=');
get[tmp[0]] = unescape(decodeURI(tmp[1]));
}//::END for
return get;
}//::END if
}//::END getGET
/**
* [DOMContentLoaded]
* @param {[const]} valores [Cogemos los valores pasados por get]
* @return {[document.write]}
*/
document.addEventListener('DOMContentLoaded', () => {
const valores=getGET();
if(valores){
// hacemos un bucle para pasar por cada indice del array de valores
for(const index in valores){
document.write(`<br>clave: ${index} - valor: ${valores[index]}`);
}//::END for
}else{
// no se ha recibido ningun parametro por GET
document.write("<br>No se ha recibido ningún parámetro");
}//::END if
});//::END DOMContentLoaded