使用 JavaScript 获取值 GET OR POST 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1961069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:07:08  来源:igfitidea点击:

Getting value GET OR POST variable using JavaScript?

javascript

提问by Mohit Jain

How to get value of the get or post variable on page load using JavaScript?

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

回答by Igor Zinov'yev

You can't get the value of POST variables using Javascript, although you can insert it in the document when you process the request on the server.

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

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

GET variables are available through the window.location.href, and some frameworks even have methodsready to parse them.

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

回答by Gumbo

You can only get the URI arguments with JavaScript.

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

回答by David Spector

The simplest technique:

最简单的技术:

If your form action attribute is omitted, you can send a form to the same HTML file without actually using a GET HTTP access, just by using onClick on the button used for submitting the form. Then the form fields are in the elements array document.FormName.elements . Each element in that array has a value attribute containing the string the user provided (For INPUT elements). It also has id and name attributes, containing the id and/or name provided in the form child elements.

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

回答by The Great

This is my first Answer in stackoverflow and my english is not good. so I can't talk good about this problem:)

这是我在 stackoverflow 中的第一个答案,我的英语不好。所以我不能很好地谈论这个问题:)

I think you might need the following code to get the value of your or tags.

我认为您可能需要以下代码来获取您的或标签的值。

this is what you might need:

这是您可能需要的:

HTML

HTML

<input id="input_id" type="checkbox/text/radio" value="mehrad" />

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

JavaScript

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";
  }
}

also, you can use other codes or other if in this function like this:

此外,您可以在此功能中使用其他代码或其他代码,如下所示:

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";
  }
}

and you can use this function in your page by events like this:

您可以通过以下事件在您的页面中使用此功能:

<div onclick="checkvalue('input_id','writeSomthing')"></div>

I hope my code will be useful for you

我希望我的代码对你有用

Write by <Mehrad Karampour>

撰稿人 <Mehrad Karampour>

回答by Marco

When i had the issue i saved the value into a hidden input:

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

in html body:

在 html 正文中:

    <body>
    <?php 
    if (isset($_POST['Id'])){
      $fid= $_POST['Id']; 
    }
    ?>

... then put the hidden input on the page and write the value $fid with php echo

...然后将隐藏的输入放在页面上并用 php echo 写入值 $fid

    <input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">

then in $(document).ready( function () {

然后在 $(document).ready( function () {

    var postId=document.getElementById("fid").value;

so i got my hidden url parameter in php an js.

所以我在 php 和 js 中得到了我隐藏的 url 参数。

回答by Copes

With little php is very easy.

用小php是很容易的。

HTML part:

HTML部分:

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

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

JavaScript

JavaScript

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

回答by jorgedipra

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

回答by jorgedipra

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

回答by imcdnzl

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.

这是我对此的回答,给出了一个类似于http://host.com/?param1=abc¶m2=cde的字符串 returnURL 。这是相当基本的,因为我开始使用 JavaScript(这实际上是我在 JS 中的第一个程序的一部分),并且使它更容易理解而不是棘手。

Notes

笔记

  • No sanity checking of values
  • Just outputting to the console - you'll want to store them in an array or something
  • this is only for GET, and not 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;
            }
        }
    }
    
  • 没有对值进行完整性检查
  • 只是输出到控制台 - 你会想要将它们存储在一个数组或其他东西中
  • 这仅适用于 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;
            }
        }
    }