26

タグを取得しようとしています-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

オートコンプリートのソースとして使用されるをavailableTagsオーバーロードしているため、を削除する必要があります。tagSource

また、それはタイプミスかもしれませんが、それは「return」ではなく「eturn」です。

編集:

問題は、あなたが提供した関数がtagSource何も返さないように見えることだと思います。しかし、私のjavascriptの知識はここで終わるようです:/

于 2011-08-04T09:14:46.857 に答える
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 に答える
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 に答える