使用JavaScript获取GET或POST变量的值?

44

如何使用JavaScript在页面加载时获取get或post变量的值?


相关的内容:https://dev59.com/AXM_5IYBdhLWcg3wXx5N - Adriano
9个回答

61

你不能使用JavaScript获取POST变量的值,尽管在服务器处理请求时可以将其插入文档中。

<script type="text/javascript">
    window.some_variable = '<?=$_POST['some_value']?>'; // That's for a string
</script>

通过 window.location.href 可以获取 GET 变量,而一些框架甚至有已准备好的 方法 可以解析它们。


12
可以使用json_encode来代替直接编写POST值。 - Ken Keenan
@Ken Keenan:你说得对,谢谢!在此之前,你也可以进行一些验证。我只是想表达我的观点。 - Igor Zinov'yev
4
不进行任何编码或验证意味着该代码容易受到 XSS 攻击。请参考 OWASP 官方网站 了解更多信息。 - Quentin

22

只有使用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("+", " "));
    }
}

1
这是我在stackoverflow上的第一个回答,我的英语不好。因此,我无法很好地谈论这个问题 :)
我认为您可能需要以下代码来获取您的标签的值。
这就是您可能需要的: HTML
<input id="input_id" type="checkbox/text/radio" value="mehrad" />

<div id="writeSomething"></div>

JavaScript
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>

0

最简单的技巧:

如果您省略了表单操作属性,只需在用于提交表单的按钮上使用 onClick,就可以将表单发送到同一HTML文件,而无需实际使用GET HTTP访问。然后,表单字段位于元素数组document.FormName.elements中。该数组中的每个元素都有一个value属性,其中包含用户提供的字符串(对于INPUT元素)。它还具有id和name属性,其中包含表单子元素中提供的id和/或name。


-1

这是我对于给定一个字符串returnURL的答案,该字符串类似于http://host.com/?param1=abc&param2=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;
            }
        }
    }
    

-1
// 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

1
它与POST有什么关系? - Putnik

-1

当我遇到这个问题时,我将该值保存到了一个隐藏的输入框中:

在 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 参数。


1
这是不安全的。它允许任何人在您的应用程序中插入任意HTML(他们可以发布"并打破属性)。 - Mark Fowler

-1

使用少量的 PHP 非常容易。

HTML 部分:

<input type="text" name="some_name">

JavaScript

<script type="text/javascript">
    some_variable = "<?php echo $_POST['some_name']?>";
</script>

1
这是完全不安全的。如果有人发布包含 " 的内容,那么他们可以跟随任意JavaScript。 - Mark Fowler
请注意仅转义 " 是不够的,还需注意防范 </script>。建议使用 json_encode(现在转义反斜线) - Mark Fowler
一种安全的技术是在PHP中编写一个函数,扫描$_POST中的参数,并将每个参数作为全局变量(或类静态变量)添加“Arg”后缀到其名称中。这可以防止参数与您自己的全局变量具有相同的名称。因此,参数“a”将在程序代码中变为变量“$aArg”。如果有人需要,我会在请求时将代码发布在这里作为答案。永远不要像您在这里所做的那样直接将用户输入包含在任何HTML或JavaScript中。这是被黑客攻击的确定方式,但很好。 - David Spector

-1

/**
* 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


它与POST有什么关系? - Putnik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接