在加载之前我需要用户点击该按钮的id

时间:2017-07-11 17:34:16

标签: javascript ajax

我尝试了几种不同的方法,比如创建一个名为check()的函数,它被称为onclick,它给出了按钮的id。但我需要该id来获取用户选择的按钮的值,并将其传递给另一个在加载时调用的函数中的变量。这里的问题是getelementbyid标签不识别来自check函数的变量,因为它是在点击时调用的,而包含getelementbyid的函数被称为onload

代码:

<?php
header('Content-Type: text/xml');
echo'<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food=$_GET['food'];
//food=$_GET['food'];
// $choice=$_GET['choice'];
// echo "yes".$cold;

$foodarray=array('tuna','Bacon','beef');
if(in_array($food,$foodarray)) {
    echo "we do have".$food."!";
}
elseif(empty($food)) {
    echo "ENter a food";
}
else {
    echo "aint got ".$food;
}
echo'</response>';
?>

foodstore.html

<!DOCTYPE html>
<html>
   <head>
     <script type="text/javascript" src="foodstore.js"></script>
   </head>
   <body onload="process()">

       Type:
  <input type="radio" id="ge1" value="member" onclick=check() name="type">member
  <input type="radio" id="ge2" value="user" onclick=check() name="type">user

<div id="underInput"/></div>
</body>
</html>

foodstore.js

var xmlHttp = createXmlHttpRequestObject();
var z="";
function createXmlHttpRequestObject(){
    var xmlHttp;

    if(window.XMLHttpRequest) {
        xmlHttp= new XMLHttpRequest();
    } else {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlHttp;
}

function check() {
    var yos=document.getElementsByName("type");
    var len=yos.length;
    for(i=0;i<len;i++) {
        if(yos[i].checked) {
            z=yos[i].value;
        }
    }
    alert(z);
}

function process() {
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
        food = encodeURIComponent(document.getElementById(z).value);
        xmlHttp.open("GET", "foodstore.php?food="+food,true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);
    } else{
        setTimeout('process()',1000);//cekaj 1s pa probaj opet
    }
}

function handleServerResponse(){
    if(xmlHttp.readyState==4){ 
        if(xmlHttp.status==200){
            var xmlResponse = xmlHttp.responseXML; 
            root = xmlResponse.documentElement;
            message = root.firstChild.data;
            kat=document.getElementById("underInput");
            kat.innerHTML+= message;
            //setTimeout('process()', 1000);
        } else {
            alert('Someting went wrong !');
        }
    }
}

1 个答案:

答案 0 :(得分:0)

this传递给功能

function check(el) {
  console.log(el.id, 'clicked')
}
<label>
   <input type="radio" id="ge1" value="member" onclick=check(this) name="type">
   member
</label>
<label>
    <input type="radio" id="ge2" value="user" onclick=check(this) name="type">
    user
</label>