26

试图让tag-it与 ajax 调用一起工作。

到目前为止一切正常。除了,我无法通过 ajax 调用分配 tagSource。

在萤火虫中,“数据”正在返回:

["Ruby","Ruby On Rails"]

但是当我在输入框中输入时它没有显示出来。

$('.tags ul').tagit({
  itemName: 'question',
  fieldName: 'tags',
  removeConfirmation: true,
  availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],
  allowSpaces: true,
  // tagSource: ['foo', 'bar']
  tagSource: function() {
    $.ajax({
      url:        "/autocomplete_tags.json",
      dataType:   "json",
      data:       { term: 'ruby' },
      success:    function(data) {
        console.log(data);
        return data;
      }
    });
  }
});

console.log(data)返回["Ruby", "Ruby On Rails"]

我在这里错过了什么吗?其他人有这个工作吗?

4

7 回答 7

39

似乎这个问题很久没有回答了,我敢打赌你已经找到了解决方案,但对于那些还没有的人,我的答案是:

当我从我的代码中复制时,缩进变得一团糟;)

<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true">
Tags:<br>
<ul id="mytags"></ul>

<script type="text/javascript">
    jQuery(document).ready(function() {
    jQuery("#mytags").tagit({
        singleField: true,
        singleFieldNode: $('#mySingleField'),
        allowSpaces: true,
        minLength: 2,
        removeConfirmation: true,
        tagSource: function( request, response ) {
            //console.log("1");
            $.ajax({
                url: "search.php", 
                data: { term:request.term },
                dataType: "json",
                success: function( data ) {
                    response( $.map( data, function( item ) {
                        return {
                            label: item.label+" ("+ item.id +")",
                            value: item.value
                        }
                    }));
                }
            });
        }});
    });

而“search.php”实际上可以在一些自动完成的 jQuery 示例中找到。

<?php
$q = strtolower($_GET["term"]);
if (!$q) return;

$items = array(
    "Great Bittern"=>"Botaurus stellaris",
    "Little Grebe"=>"Tachybaptus ruficollis",
    "Black-necked Grebe"=>"Podiceps nigricollis",
    "Little Bittern"=>"Ixobrychus minutus",
    "Black-crowned Night Heron"=>"Nycticorax nycticorax",
    "Heuglin's Gull"=>"Larus heuglini"
);

function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

        // We first copy each key/value pair into a staging array,
        // formatting each key and value properly as we go.

        // Format the key:
        if( is_numeric($key) ){
            $key = "key_$key";
        }
        $key = "\"".addslashes($key)."\"";

        // Format the value:
        if( is_array( $value )){
            $value = array_to_json( $value );
        } else if( !is_numeric( $value ) || is_string( $value ) ){
            $value = "\"".addslashes($value)."\"";
        }

        // Add to staging array:
        $construct[] = "$key: $value";
    }

    // Then we collapse the staging array into the JSON form:
    $result = "{ " . implode( ", ", $construct ) . " }";

} else { // If the array is a vector (not associative):

    $construct = array();
    foreach( $array as $value ){

        // Format the value:
        if( is_array( $value )){
            $value = array_to_json( $value );
        } else if( !is_numeric( $value ) || is_string( $value ) ){
            $value = "'".addslashes($value)."'";
        }

        // Add to staging array:
        $construct[] = $value;
    }

    // Then we collapse the staging array into the JSON form:
    $result = "[ " . implode( ", ", $construct ) . " ]";
}

return $result;
}

$result = array();
foreach ($items as $key=>$value) {
    if (strpos(strtolower($key), $q) !== false) {
    array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
    break;
}
echo array_to_json($result);

?>
于 2011-08-16T21:04:47.683 回答
13

看看这个: 如何让 tagSource 与 $.ajax() 一起工作?(来自标记-它的 github 问题列表)。

这是一个示例: HTML 文件:

<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
$(document).ready(function() {
$("#mytags").tagit({
  tagSource: function(search, showChoices) {
    $.ajax({
      url: "auto.php",
      data: {search: search.term},
      success: function(choices) {
        showChoices(choices);
      }
    });
  }
});
});
</script>
</head>
<body>
<ul id="mytags">
<li>Tag1</li>
</ul>
</body>
</html>

(从 [这里][1] 获取 tag-it.js 文件)

这是PHP文件:

<?php
header('Content-type: application/json');
$q = $_GET["search"];
//check $q, get results from your database and put them in $arr
$arr[] = 'tag1';
$arr[] = 'tag2';
$arr[] = $q;
echo json_encode($arr);
?>
于 2011-10-05T14:02:49.020 回答
8

这些答案都没有对我有用,所以我想我会回来发布我的有效代码。

var tagThis = $(".tagit");
tagThis.tagit({
    tagSource: function(search, showChoices) {
        $.ajax({
            url: "/tags/search",
            data: { search: search.term },
            dataType: "json",
            success: function(data) {
                var assigned = tagThis.tagit("assignedTags");
                var filtered = [];
                for (var i = 0; i < data.length; i++) {
                    if ($.inArray(data[i], assigned) == -1) {
                        filtered.push(data[i]);
                    }
                }
                showChoices(filtered);
            }
        });
    }
});

此代码假定 URL 返回 JSON 编码字符串(字符串数组)。然后它将过滤掉输入中已经选择的任何标签。所以它们不会在列表中重复。否则,这对我有用。

感谢其他人让我走上正确的道路。

于 2012-04-15T00:56:56.793 回答
5

tagSource 已贬值。

只需使用:

<script>
  $(document).ready(function(){
      $("#tagit").tagit({
     autocomplete: {
    source: "your-php-file.php",
     }
   });
  });
</script>

您可以将所有属性添加到此:

<script>
  $(document).ready(function(){
      $("#tagit").tagit({
         allowSpaces: true,
         singleFieldDelimiter: ';',
         allowDuplicates: true,
         autocomplete: {
           source: "your-php-file.php",
     }
   });
  });
</script>
于 2013-06-28T14:03:44.240 回答
1

我认为您可以从 jquery UI 覆盖自动完成方法:

$('.tags ul').tagit({

    itemName: 'question',
    fieldName: 'tags',
    removeConfirmation: true,
    //availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
    allowSpaces: true,
    // tagSource: ['foo', 'bar']
    tagSource: function () {
        $.ajax({
            url: "/autocomplete_tags.json",
            dataType: "json",
            data: {
                term: 'ruby'
            },
            success: function (data) {
                console.log(data);
                return data;
            }

        });
    },
    autocomplete: {
        delay: 0,
        minLength: 2,
        source: this.tagSource()
    }
});
于 2013-03-09T16:41:27.863 回答
1

您应该删除您的availableTags, 因为您正在重载tagSource,它用作自动完成的源。

这也可能是一个错字,但它是“ return”,而不是“ eturn”。

编辑:

我认为问题在于您提供的功能tagSource似乎没有返回任何内容。但是我的 javascript 知识似乎到此结束:/

于 2011-08-04T09:14:46.857 回答
0

只是添加

假设您的脚本页面看起来像

<script>
  $(document).ready(function(){
      $("#myULTags").tagit({
         allowSpaces: true,
         singleFieldDelimiter: ';',
         allowDuplicates: true,
         autocomplete: {
           source: "searchtag.php",
     }
   });
  });
</script>  

如果您从数据库中获取值,您的简单 php 页面看起来像

<?php $link = mysqli_connect("localhost","root","dbpassword","dbname") or die("Couldn't make connection."); ?>

<?php
$q = strtolower($_GET["term"]);
if (!$q) return;

header('Content-type: application/json');


$query_tags = mysqli_query($link,"SELECT TagName FROM `tagstable` WHERE `TagName` LIKE '%".$q."%' LIMIT 10");

$items = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($query_tags)){ 

  $items[] = $row['TagName']; // add the row in to the results (data) array

}

echo json_encode($items);

?>

问候

于 2016-09-11T19:40:14.557 回答