Getting value GET OR POST variable using JavaScript?

前端 未结 9 1470
一个人的身影
一个人的身影 2020-11-27 05:59

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

相关标签:
9条回答
  • 2020-11-27 06:48

    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.

    <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 methods ready to parse them.

    0 讨论(0)
  • 2020-11-27 06:50

    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.

    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;
              }
          }
      }
      
    0 讨论(0)
  • 2020-11-27 06:55

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

    in html body:

        <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

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

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

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

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

    0 讨论(0)
提交回复
热议问题