读书人

select下拉框的数据是在ajax里面生成的

发布时间: 2013-04-21 21:18:07 作者: rapoo

select下拉框的数据是在ajax里面生成的,如何才能取得并上传所选的值
有这么一个情况,下拉框里的选项是后台动态生成的,所以下拉框的代码没有在html里面写,而是写在ajax里面。那这种情况下,我该如何取得用户所选的值并上传到后台某个php中呢?
html的代码(selectdata.html):

<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="selectdata.js"></script>
<script type="text/javascript">
$(document).ready(function(){
showselect($("select"));
});
</script>
</head>
<body>
<div id="select" name="select "class="select"></div>
<input type="submit" class="button" value="echo" />
</body>
</html>


ajax的代码(selectdata.js):
function showselect(htmlContainer){
$.ajax({
url:"selectdata.php",
type:"post",
dataType:"json",
success:function(data){
var select = document.createElement("select");
for(var name in data.sex){
var option = document.createElement("option");
option.name = name;
option.innerHTML = name;
option.value = data.sex[name];
select.appendChild(option)
}
document.getElementsByTagName("body")[0].appendChild(select)
}
});
}


后台生成select数据部分的php文件():
<?php
include ("JSON.php");
$json = new Services_JSON();

$arr = array("sex select"=>"","man"=>"male","woman"=>"famale","other"=>"other");
$str = array("sex"=>$arr);

$json = json_encode($str);
echo $json;


?>



后台数据如下(json格式的):
[root@localhost select]# php selectdata.php 
{"sex":{"sex select":"","man":"male","woman":"famale","other":"other"}}



这种环境下,能够实现,将用户选择某个值后点击某个按钮,上传给某个php文件,这个功能吗? ajax php javascript
[解决办法]
用jquery获取select的值提交就行了

<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="selectdata.js"></script>
<script type="text/javascript">
$(document).ready(function () {
showselect($("select"));
});
function postSelect() {
var v = $('#select').val();
$.post('xxxxxxx.php', { select: v }, function (data) { alert('提交成功'); });
}
</script>
</head>
<body>
<div id="select" name="select "class="select"></div>
<input type="submit" class="button" value="echo" onclick="postSelect()" />
</body>
</html>
[解决办法]
$('#select').val(); 试试。。。。

读书人网 >Ajax

热点推荐