使用javascript获取url参数并将其发送到php

时间:2013-06-23 20:40:57

标签: php javascript html

标题非常清楚我正在尝试做什么。我想在URL中检索变量vavlue,然后将其发送到add.php。

我不是简单地将PHP代码放在html中的原因是因为FORM也将var发送到add.php

PHP代码:

<?php

$id = $_POST["id"];

 ?>

blabla.html中的Javascript?id = test

    <script>
 function getResults()
 {
  var xmlhttp;
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }
  else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  document.getElementById("here").innerHTML=xmlhttp.responseText;
  }
 }
 var id = getParameterByName("id");
 var data = "id="+document.getElementById("id").value;

 xmlhttp.open("POST","add.php",true);
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send(data);
 }
</script>

<script>
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>

2 个答案:

答案 0 :(得分:0)

var data = "id="+document.getElementById("id").value;
                                         ^^^^--string containing the letters 'i' and 'd'

应该是

var data = "id="+document.getElementById(id).value;
                                         ^^-- variable named "id"

答案 1 :(得分:0)

尝试此功能

function getParameterByName( name ) {
  var parts = window.location.search.substr(1).split("&");
  var p_arr = {};
  for( var i = 0; i < parts.length; i++ ) {
    var temp = parts[i].split("=");
    if ( decodeURIComponent( temp[0] ) != "" ) {
      p_arr[decodeURIComponent( temp[0] )]  = decodeURIComponent( temp[1] );
    }
  }
  return p_arr[name];
}

function getResults() {
  var xmlhttp;
  if ( typeof XMLHttpRequest !== 'undefined' ) {
    xmlhttp = new XMLHttpRequest();
  }
  else {
    var versions  = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
    for( var i = 0, len = versions.length; i < len; i++ ) {
      try {
        xmlhttp = new ActiveXObject( versions[i] );
        break;
      }
      catch(e) {}
    }
  }

  xmlhttp.onreadystatechange  = function() {
    if ( this.readyState === 4 && this.status == 200 ) {
      document.getElementById( "here" ).innerHTML = xmlhttp.responseText;
    }
  };

  var id    = getParameterByName( "id" );
  var data  = "id="+document.getElementById( id ).value;

  xmlhttp.open( "POST", "add.php", true );
  xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
  xmlhttp.send( data );
}