【问题标题】:Dynamic select option with Ajax, json and PHP keep option selected after submit提交后选择 Ajax、json 和 PHP 保持选项的动态选择选项
【发布时间】: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 :)
  • 我正在准备一个包含多个选项的答案 ;)
  • 等不及了!多个选项是最好的。 :)

标签: php json ajax


【解决方案1】:

选项 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 脚本中,处理帖子和页面渲染似乎是相同的,您可以在 &lt;select&gt; 上添加一个 data 属性,指定默认选定值

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

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

$.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:我看到你把name从JSON放到&lt;option&gt;值,应该有ID,然后根据数据选择的值检查ID(使用POST发送到服务器的那个) )

【讨论】:

  • Option 2 的唯一问题是我得到一个解析错误,如果出现意外令牌。你的意思是 Ajax 代码还是 PHP?
  • 你能说得更具体些吗?选项二只是 PHP / HTML / JavaScript 并稍微改变你的 AJAX 响应回调(添加对先前选择的值的检查)
  • 在线解析错误$select.append('&lt;option value="' + val.name + '"' + (if(val.name == $select.data('selected')) ? ' selected' : '') + '&gt;' + val.name + '&lt;/option&gt;');
  • 是的,愚蠢的我,对不起:$select.append('');
  • 好的,但是我需要在form而不是select中选择PHP返回的data-selected$select.data('selected')是未定义的,永远没有位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多