【问题标题】:Getting value GET OR POST variable using JavaScript?使用 JavaScript 获取值 GET 或 POST 变量?
【发布时间】:2010-12-29 23:37:40
【问题描述】:

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

【问题讨论】:

标签: javascript


【解决方案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>

希望我的代码对你有用

&lt;Mehrad Karampour&gt;写信

【讨论】:

    【解决方案2】:

    最简单的技术:

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

    【讨论】:

      【解决方案3】:

      这是我的答案,给定一个类似于http://host.com/?param1=abc&param2=cde 的字符串returnURL。这是相当基本的,因为我刚开始学习 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;
                }
            }
        }
        

      【讨论】:

        【解决方案4】:

        /**
        * 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有什么关系?
        【解决方案5】:
        // 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
        

        【讨论】:

        • 和POST有什么关系?
        【解决方案6】:

        用一点点php很容易。

        HTML 部分:

        &lt;input type="text" name="some_name"&gt;

        JavaScript

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

        【讨论】:

        • 这完全不安全。如果有人发布了包含 " 的内容,那么他​​们可以使用任意 JavaScript 来关注它。
        • 还要注意,转义"是不够的,还需要提防&lt;/script&gt;。建议使用json_encode(现在转义反斜杠)
        • 一种安全的技术是在 PHP 中编写一个函数,该函数扫描 $_POST 中的参数,并使每个参数成为全局变量(或类静态变量),并在其名称后附加“Arg”。这可以防止参数与您自己的全局变量之一具有相同的名称。因此,参数“a”将成为程序代码中的变量“$aArg”。如果有人需要,我会在此处发布代码作为答案。切勿像您在此处所做的那样将用户输入直接包含在任何 HTML 或 JavaScript 中。这是被黑的肯定方法,但很好。
        【解决方案7】:

        当我遇到问题时,我将值保存到隐藏输入中:

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

        【讨论】:

        • 这是不安全的。它允许任何人在您的应用程序中插入任意 HTML(他们可以发布 " 并突破属性)
        【解决方案8】:

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

        【讨论】:

          【解决方案9】:

          您无法使用Javascript获取POST变量的值,尽管您可以在服务器上处理请求时将其插入到文档中。

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

          GET 变量可以通过window.location.href 获得,一些框架甚至有methods 准备好解析它们。

          【讨论】:

          • 你可以使用json_encode而不是直接写POST值
          • @Ken Keenan:你说得对,谢谢!而且您还可以在此之前进行一些验证。我只是想表明我的观点。
          • 不进行任何类型的编码或验证意味着编写的代码是vulnerable to XSS
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-01-11
          • 1970-01-01
          • 1970-01-01
          • 2013-07-13
          • 1970-01-01
          • 1970-01-01
          • 2012-08-16
          相关资源
          最近更新 更多