提交后使用Ajax、json和PHP keep选项进行动态选择

时间:2022-09-25 15:00:15

I have a simple dynamically generated select option with Ajax from a json file, what I failed to do is to keep the formerly selected option as selected after submitting the form. Tried that with PHP variable sent to JS but I couldn't find a way to use PHP code inside script tag and echo-ing everything with PHP is ugly. Any idea?

我有一个用json文件中的Ajax动态生成的选择选项,但我没能做到的是在提交表单后保留先前选择的选项。用发送给JS的PHP变量尝试过,但我找不到在脚本标记中使用PHP代码的方法,用PHP进行所有的回调都很难看。任何想法?

My PHP + AJAX code:

我的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>

My JSON file:

我的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 个解决方案

#1


1  

Option 1:

选项1:

Use AJAX for the submit as well, in this way there will be NO page (re)load and the select will keep the previous value as desired.

对于提交也使用AJAX,这样就不会加载页面(重新),select将保持先前的值。

$("#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'
    )
})

Your response from the server 'yourServerScript.php' which consumes your post data, should return something like:

您的响应来自服务器的“yourServerScript”。使用您的post数据的php'应该返回如下内容:

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

{“成功”:或真或假,…您想在处理表单后发送的其他数据…}

Option 2:

选项2:

You can still send the post normally and the page will (re)load from the server the process result of the form data, and in this case, to keep selected the value(s) previously selected you have again multiple options, but I will present to you only an elegant one:

您仍然可以正常地发送邮件,页面将从服务器重新加载表单数据的处理结果,在这种情况下,为了保持先前选择的值,您将再次拥有多个选项,但我只向您提供一个优雅的选项:

From your PHP script, which seems to be the same for processing the post and the page render, you can add a data attribute on the <select> which specifies the default selected value(s)

在PHP脚本中,处理post和页面呈现似乎是一样的,您可以在

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

Then, in your AJAX script which loads the JSON and populates the select with options, you check for this data-selected attribute

然后,在加载JSON并使用选项填充select的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: I see that you put the name from the JSON to the <option> value, there should be the ID, and then check the ID against the data-selected value (the one sent to the server using POST)

PS:我看到你把名字从JSON放到

#1


1  

Option 1:

选项1:

Use AJAX for the submit as well, in this way there will be NO page (re)load and the select will keep the previous value as desired.

对于提交也使用AJAX,这样就不会加载页面(重新),select将保持先前的值。

$("#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'
    )
})

Your response from the server 'yourServerScript.php' which consumes your post data, should return something like:

您的响应来自服务器的“yourServerScript”。使用您的post数据的php'应该返回如下内容:

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

{“成功”:或真或假,…您想在处理表单后发送的其他数据…}

Option 2:

选项2:

You can still send the post normally and the page will (re)load from the server the process result of the form data, and in this case, to keep selected the value(s) previously selected you have again multiple options, but I will present to you only an elegant one:

您仍然可以正常地发送邮件,页面将从服务器重新加载表单数据的处理结果,在这种情况下,为了保持先前选择的值,您将再次拥有多个选项,但我只向您提供一个优雅的选项:

From your PHP script, which seems to be the same for processing the post and the page render, you can add a data attribute on the <select> which specifies the default selected value(s)

在PHP脚本中,处理post和页面呈现似乎是一样的,您可以在

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

Then, in your AJAX script which loads the JSON and populates the select with options, you check for this data-selected attribute

然后,在加载JSON并使用选项填充select的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: I see that you put the name from the JSON to the <option> value, there should be the ID, and then check the ID against the data-selected value (the one sent to the server using POST)

PS:我看到你把名字从JSON放到