【问题标题】:How to refresh a dropdown field in a form without freshing the entire form using ajax?如何在不使用ajax刷新整个表单的情况下刷新表单中的下拉字段?
【发布时间】:2019-09-17 21:47:51
【问题描述】:

有一个表单,其中一个字段是一个下拉字段,其中包含数据库中的项目名称。

有一个添加新项目的规定,通过点击“添加新”按钮,会出现一个弹出窗口,我们可以保存新项目。

虽然保存在数据库中,但在下拉字段中并没有体现出来,所以需要刷新。但是刷新整个页面会导致其他字段中输入的值丢失。

我的问题是,如何只刷新这个下拉字段而不刷新整个表单?

【问题讨论】:

  • 到目前为止你做了什么?
  • 您使用 select2 的哪个下拉菜单或应该添加代码的普通下拉菜单
  • @Viswa 我已经完成了整个编码。它是 Yii 框架。我第一次使我的代码这样当添加一个新项目时,整个页面都会被刷新。由于那不是我尝试使用 ajax 的正确方法。现在唯一的问题是刷新下拉字段。
  • @Muhammad Omer Aslam,我正在使用带有实时搜索选项(data-live-search)的下拉菜单,因此将有一个文本框以及
  • 这将是使用Select2下拉插件时?

标签: php mysql ajax yii dropdownbox


【解决方案1】:

我遇到了同样的问题,但有一个通知框,所以我在它上面附加了一个事件,它通过点击它开始。此事件正在向 PHP 文件发送一些信息,并且 PHP 文件以来自数据库的通知进行响应。您也可以这样做,当用户单击下拉字段时,将使用 ajax 将请求发送到 PHP 文件以从数据库中获取信息,并且在用户添加项目并保存后,如果他在下拉菜单上单击以关闭它一个请求将被发送到数据库以获取所需的信息。或者您甚至可以将事件附加到显示“保存”或其他内容的按钮上,因此当他单击保存时,将发送请求并将响应附加到下拉菜单的内容中而无需重新加载。

我的代码如下: jQuery:-

// the event click is attached to the icon of the notification through its class 
$('.icon').click(function () {
//I used this line to make the hidden notification box slide down to show content
    $('#notifications-box').slideToggle(400);
//here the ajax request will be sent on the click
    $.ajax({
// The method of sending the data is POST because it is more seucre
        method: "POST",
//the File that you want to the send the data to 
        url: "get_notifications.php",
// The data that needs to be sent
        data: {
            //the name       : // the value 
            get_notifications: "true"
        },
// then on success the return will be appended to the notification box ( status is the respond )
        success: function (status) {
            $('.notifications-box').append(status);
        }
    });
});

然后你可以在php文件中使用isset()来知道数据是否是通过使用ajax请求发送到php文件的

//isset($_method(POST / GET)['您发送的名称在ajax请求中数据对象的大括号内'])

isset($_POST['get_notifications'])

【讨论】:

    【解决方案2】:

    要在 jQuery 的下拉框中添加新元素,请使用下面的代码,将元素 ID、a_value 和 a_text 替换为正确的信息(来自“添加新”按钮的输入信息)。

    let dropdown = $('#dropdown');
    dropdown.append($('<option></option>').attr('value', a_value).text(a_text));
    

    或者:

    $('#dropdown').append($('<option></option>').attr('value', a_value).text(a_name));
    

    【讨论】:

    • 我正在使用带有实时搜索选项 (data-live-search) 的 yii 下拉菜单,因此在下拉列表中将有一个带有
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多