<?php
include('connection.php');
$query="select * from category";
$result=mysql_query($query,$conn);
echo'
<select name="category" id="uni" >';
//The select tag start here,It gets options from Database
while($catrow=mysql_fetch_array($result)) {
echo'<option value="">';
echo'<option value="'.$catrow['Id'].'">'.$catrow['Name'].
'</option></form>';
}
echo'</select>';
?><br />
现在我有这样的ajax代码,我知道如何用ajax获取输入值,但我不知道如何用ajax获取select标签值。
我将这行代码用于输入类型:
function checkUser() {
var str=document.form.category.value;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request");
return;
}
//this line is where I get inputs value,how can I get Select tag's?????!!!
url='addserv.phptitle='+document.getElementById('title').value+document.getElementById('latitude').value+document.getElementById('ownerId').value;
//alert(url);
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState==4 ){
var name = xmlHttp.responseText;
}
}
答案 0 :(得分:0)
如果您的PHP回显正确的标记并且您想将其附加到DOM,那么您可以这样做:
$.ajax({
type: 'GET',
url: 'something.php',
success: function(data) {
$('.someElement').html(data);
}
});
答案 1 :(得分:0)
另一种不需要JQuery但只需要javascript的方法就是这样:
var req = new XMLHttpRequest();
req.open('GET', 'http://example.com/script.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4 && req.status == 200) {
YourElementId.innerHTML = req.responseText;
}
};
req.send(null);
其中YourElementID
将是您要修改的元素的ID,例如<select>
元素和script.php
应返回JSON字符串(推荐)或直接返回您想要的标记放入<select>
元素。
您可以参考this answer了解更多信息。
使用JSON进行更新:
你的php和接收文件应该是这样的:
<强>的script.php 强>:
<?php
$responseArray = array(
'option1' => 'option one'
'option2' => 'option two'
'option3' => 'option three'
'option4' => 'option 4'
);
$jsonResponse = json_encode($responseArray);
echo $jsonResponse;
?>
<强> document.html 强>:
<header>
<script type="text/javascript">
function loadOptions() {
var req = new XMLHttpRequest();
req.open('GET', 'script.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4 && req.status == 200) {
responseObject = JSON.parse(req.responseText);
for (var key in responseObject) {
Select.innerHTML += '<select value="'+key+'">'+responseObject[key]+'</select>';
}
}
};
req.send(null);
}
</script>
</header>
<body onload="loadOptions();">
<select id="Select">
</select>
</body>