2

标题对我正在尝试做的事情非常明确。我想检索 URL 中的变量 vavlue,然后将其发送到 add.php。

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

PHP代码:

<?php

$id = $_POST["id"];

 ?>

blabla.html?id=test 中的 Javascript

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

2 回答 2

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"
于 2013-06-23T20:43:41.020 回答
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 );
}
于 2013-06-23T20:56:45.917 回答