【发布时间】:2016-07-13 02:16:22
【问题描述】:
我有一个简单的从 json 文件中使用 Ajax 动态生成的选择选项,我没有做的是在提交表单后保持以前选择的选项为选中状态。尝试将 PHP 变量发送到 JS,但我找不到在脚本标签中使用 PHP 代码的方法,并且用 PHP 回显所有内容都很丑陋。有什么想法吗?
我的 PHP + AJAX 代码:
ini_set('display_errors', -1);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo '<pre>';
var_dump($_POST);
echo '</pre>';
}
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<form id="getsrc" method="post">
<select name="links" id="links"></select>
</form>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#links');
//request the JSON data and parse into the select element
$.ajax({
url: 'links.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$select.append('<option value="">Please select...</option>');
$.each(data.link, function(key, val){
$select.append('<option value="' + val.name + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
$("#links").change(function(){
this.form.submit();
});
</script>
</html>
我的 JSON 文件:
{"link": [
{
"id": "1",
"name": "link1.html"
},
{
"id": "2",
"name": "link2.html"
},
{
"id": "3",
"name": "link3.html"
},
{
"id": "4",
"name": "link4.html"
},
{
"id": "5",
"name": "link5.html"
}
]}
【问题讨论】:
-
如果您使用 AJAX 获取 JSON 数据(到服务器的额外往返,而不是使用 PHP 解析 JSON 并呈现完整形式),您为什么不使用 AJAX 作为提交好吧 ?在这种情况下,将没有页面(重新)加载,您的选择将保持所选值...
-
这些是我的作业要求,否则我只会使用 PHP :)
-
我正在准备一个包含多个选项的答案 ;)
-
等不及了!多个选项是最好的。 :)