2013-06-23 89 views
2

標題對我正在嘗試做的事情非常明確。我想在URL中檢索變量vavlue,然後將其發送到add.php。使用JavaScript獲取url參數並將其發送到php

我不只是把HTML中的PHP代碼的原因是一種形式,也送無功到add.php

PHP代碼的:

<?php 

$id = $_POST["id"]; 

?> 

Javascript語言,blabla.html? ID =測試

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

回答

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" 
+0

TNX但我想已經,其假設與「合作」 – user2495097

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); 
} 
相關問題