简体   繁体   中英

How to send a Javascript/Ajax variable to a php page using AJAX

function runGetIperfSpeedAjax(speedVar, actualIp) {
    var xmlhttp = getAjaxObject();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            processIperfRequest(xmlhttp.responseText, speedVar);
        }
    }
    xmlhttp.open('GET', 'lib/getIperfSpeed.php', true);
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send();
}

function processIperfRequest(response, speedVar) {
    alert("proccess");
    document.getElementById(speedVar).style.display = 'none';
    document.getElementById('displaySpeedTest').style.display = 'block';
    document.getElementById('displaySpeedTest').innerHTML = response;
}

getAjaxObject() is not included as it is just standard. I am making an onclick JavaScript call that calls runGetIperfSpeedAjax . This all works properly if I hard set the IP in "lib/getIperfSpeed.php". But I cannot seem to pass the actualIp to "lib/getIperfSpeed.php". I tried 'lib/getIperfSpeed.php'+actualIp to attempt to pass it and access it through post.

All help is appreciated.

if you want to pass the ip as a GET value you have to add the GET key

function runGetIperfSpeedAjax(speedVar, actualIp) {
    var xmlhttp = getAjaxObject();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            processIperfRequest(xmlhttp.responseText, speedVar);
        }
    }
    xmlhttp.open('GET', 'lib/getIperfSpeed.php?ip='+actualIp, true);
    // missing in your code '&ip='+actualIp
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send();
}

function processIperfRequest(response, speedVar) {
    alert("proccess");
    document.getElementById(speedVar).style.display = 'none';
    document.getElementById('displaySpeedTest').style.display = 'block';
    document.getElementById('displaySpeedTest').innerHTML = response;
}

so in the getIperfSpeed.php you get the actualIp with ip

$_GET['ip']

if you need to pass the actualIp with POST you need to change the ajax into POST.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM