动态选择选项,Ajax、json和PHP在提交后保留选择选项


Dynamic select option with Ajax, json and PHP keep option selected after submit

我从json文件中用Ajax动态生成了一个简单的选择选项,但我没能做到的是在提交表单后将以前选择的选项保持为选中状态。我尝试过将PHP变量发送到JS,但我找不到在脚本标记中使用PHP代码的方法,用PHP回显一切都很糟糕。知道吗?

我的PHP+AAJAX代码:

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"
  }
]}

选项1:

同样使用AJAX进行提交,这样就不会有页面(重新)加载,选择将根据需要保持以前的值。

$("#links").change(function(){
    var $f = $(this).parent('form');
    $.post(
        'yourServerScript.php',
        $f.serialize(), //+ "&a=you-can-attach-extra-params-if-you-like",
        function(data, tStatus, xhr){
            // do whatever the server response is ...
            if (data.success) {
                // do whatever you want if you pass success from the server (in result JSON)
            } else {
                // here you've stated an error, deal with it ...
            }
        },
        'json'
    )
})

来自服务器"yourServerScript.php"的响应(该服务器消耗了您的帖子数据)应该返回以下内容:

{"success":true or false, ... other data that you want to send after processing the form post ...}

选项2:

你仍然可以正常发送帖子,页面将从服务器上(重新)加载表单数据的处理结果,在这种情况下,为了保持之前选择的值,你有多个选项,但我只向你展示一个优雅的选项:

从您的PHP脚本(似乎与处理帖子和页面渲染相同)中,您可以在<select>上添加一个数据属性,该属性指定默认的选定值

<form id="getsrc" method="post">
    <select name="links" id="links"<?php if(!empty($_POST['links'])) echo 'data-selected="' . $_POST['links'] . '"'; ?>></select>
</form>

然后,在加载JSON并用选项填充select的AJAX脚本中,检查该数据selected属性

$.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 == $select.data('selected') ? ' selected' : '') + '>' + val.name + '</option>');
        })
    },
    error:function(){
        //if there is an error append a 'none available' option
        $select.html('<option id="-1">none available</option>');
    }
});

PS:我看到你把JSON中的name放在<option>的值上,应该有ID,然后根据数据选择值(使用POST发送到服务器的值)检查ID