重复标记被重新创建

重复标记被重新创建

本文介绍了jQuery select2:重复标记被重新创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早些时候问了一个问题( jquery select2:error从php-mysql获取数据).但是,我正在尝试修复它,而现在却遇到了一些奇怪的问题.我不确定为什么会这样发生.

I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am not sure why it is happening like this.

下面是JavaScript代码.

Below is the JavaScript code.

<div class="form-group">
   <label class="col-sm-4 control-label">Product Name</label>
   <div class="col-sm-6">
      <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div>

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: "json",
        type: "POST",
      data: function(term) {
                        return {q: term};
                    },
                    results: function(data) {
                        return {results: data};
                    },

    },
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
        return { id: term, text: text };
    },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                console.log("Removing the tag");
                var selectedTags = $("#tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index,1);
                if (selectedTags.length == 0) {
                    $("#tags").select2("val","");
                } else {
                    $("#tags").select2("val",selectedTags);
                }
           }
        }
    }
});
</script>

这是php代码( fetch.php )

<?php
// connect to database
require('db.php');

// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
//$search='te';
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));

// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);

// Make sure we have a result
if(count($list) > 0){
   foreach ($list as $key => $value) {
    $data[] = array('id' => $value['tid'], 'text' => $value['tag']);
   }
} else {
   $data[] = array('id' => '0', 'text' => 'No Products Found');
}

// return the result in json
echo json_encode($data);

?>

select2版本为3.5

以上代码能够通过使用fetch.php从数据库发送/接收请求.

Above code is able to send/receive request from database by using fetch.php.

问题在我的数据库中,有两条记录 test &标记 temp 时,会创建新标记.

Problem is in my database there are two records test & temp when I tag any one of them it create new tag.

它应该像这样工作:如果数据库具有值,那么它将不会创建具有相同名称的新标签.

推荐答案

最后,它现在可以工作了.我要感谢@alex& @milz的支持.这是完整的n个最终代码.现在不创建重复的标签.但是,我正在努力在数据库中添加标签.

Finally it is working now. I would like to thanks @alex & @milz for their support.Here is the full n final code. Now duplicate tags are not creating. However, i am working to add tag in database.

php/html文件

<div class="form-group">
   <label class="col-sm-4 control-label">Product Name</label>
   <div class="col-sm-6">
      <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div>

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,
    tags: true,
    placeholder: "Please enter tags",
    tokenSeparators: [',', ' '],//[","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: 'json',
      //  type: "POST",
       data: function(term,page) {
                        return {
                            term: term
                           };
                    },
                    results: function(data,page) {
                         lastResults = data;
                          return {results: data};

                    },
    },
    maximumSelectionSize: 3,
    minimumInputLength: 3,
createSearchChoice: function(term) {
    console.log($(this).attr('data'));
    var text = term + (lastResults.some(function(r) {

     console.log(r.text);
      console.log(term);
      return r.text == term
    }) ? "" : " (new)");

    return {
      id: term,
      text: text
    };
  },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {

           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                console.log("Removing the tag");
                var selectedTags = $("#tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index,1);
                if (selectedTags.length == 0) {
                    $("#tags").select2("val","");
                } else {
                    $("#tags").select2("val",selectedTags);
                }
           }
        }
    }
});
</script>

这是从数据库获取数据的php文件. fetch.php

Here is the php file to get the data from database.fetch.php

<?php
// connect to database
require('db.php');

// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
//if(isset($_GET)){
$search = strip_tags(trim($_GET['term']));

// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));

$list = $query->fetchall(PDO::FETCH_ASSOC);

if(count($list) > 0){
   foreach ($list as $key => $value) {
    $data[] = array('id' => $value['tag'], 'text' => $value['tag']);
   }
} else {
   $data[] = array('id' => 'No Products Found', 'text' => 'No Products Found');
}

echo json_encode($data);

?>

花了很多时间.将近3天.我希望它可以节省一些人的精力.

It took lots of time. Almost 3 days. I hope it will save someone efforts.

这篇关于jQuery select2:重复标记被重新创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:46