【问题标题】:saving jQuery tag-it input as php array将 jQuery tag-it 输入保存为 php 数组
【发布时间】:2013-01-22 22:50:23
【问题描述】:

我正在使用 jQuery Tag-it!为我的用户创建一个“技能”输入表单。我有 tag-it 的 UI 工作,但我无法让用户输入到 PHP 数组中。我正在尝试序列化这个数组并将其保存到 mysql 数据库中以便稍后显示,但我什至无法将数据放入数组中。

这里是 javascript 初始化标记:

$('#skills').tagit({     
    allowSpaces: true,
    placeholderText: "Separate skills with a comma please",
    autocomplete: true
});

这是 HTML:

<div>
    <label class="add_label">Skills: </label>
    <ul id="skills" style="width: 275px; margin-bottom: 8px;"></ul>
</div>

这是创建应该存储用户输入的输入字段的 javascript:

if (!this.options.singleField) {
       var escapedValue = label.html();
       tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.fieldName + '" />');
}

这是获取用户输入的 PHP —— 这是不工作的部分。我无法从表单中检索任何数据:

$skillsArr = $link->real_escape_string($_POST['skills']);

当我提交表单时,mysqli 查询执行并且在数据库中我看到“N;”序列化数组应该在哪里。

如何将 jQuery Tag-it 值放入一个 PHP 数组中,我可以将其序列化并保存到 mysql 数据库中?

【问题讨论】:

  • 在某处回显 mysql 查询,或者将其转到 error_log() 以便您可以查看实际正在运行的查询。
  • 在您的 php 处理程序文件中尝试 var_dump( $_REQUEST ); 以查看您提交的数据并相应地处理它。
  • 或在控制台日志中查看使用 ajax 请求发送的帖子
  • 您能否向我们解释一下您对此问题的解决方案@TyBailey

标签: php jquery arrays jquery-ui tag-it


【解决方案1】:

问题在于,tag-it 默认会发送带有如下数据的 post 请求:

tags=foo&tags=bar&tags=blah

PHP 将通过使 $_POST['tag'] ='blah' 来解释它。为了让 PHP 像数组一样处理它,发布数据需要如下所示:

tags[]=foo&tags[]=bar&tags[]=blah

解决这个问题最简单的方法就是在设置 tag-it 时更改 fieldName 参数,例如:

$('.taglist').tagit({
    allowSpaces: true,
    placeholderText: 'add new tag here...',
    fieldName: 'tags[]'
});

通过简单地更改名称以包含 [] 然后它将被 PHP 解释为您想要的并成为一个数组。

或者,如果您无法调整,您始终可以处理原始 PHP 数据以将标签作为数组获取,例如:

$query = array();
foreach (explode('&', file_get_contents('php://input')) as $kv) {
    list($k, $v) = explode('=', $kv);
    $k = urldecode($k);
    $v = urldecode($v);
    if (!isset($query[$k])) {
        $query[$k] = $v;
    } else {
        if (is_array($query[$k])) {
            $query[$k][] = $v;
        } else {
            $query[$k] = array($query[$k], $v);
        }
    }
}

现在 $query['tags'] 将是一个预期的数组。

注意:如果只发送一个标签,那么它最终会成为带有上述代码的字符串,所以如果结果是循环或其他东西,请确保将其转换为数组:

foreach((array)$query['tags'] as $tag) ...

【讨论】:

    【解决方案2】:

    我发现在后端 (php/mysqli) 上执行所有查询更容易。

    这样我的 jQuery 自动完成功能唯一需要的是:

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

    我刚刚定义了文件的来源。您可以根据需要添加分隔符等(我只是修改了源代码)。

    但主要功能来自于 php 文件,该文件返回 JSON 编码结果。

    <?php
    include("dbconnect.php"); //Including our DB Connection file
    
        if ( !isset($_REQUEST['term'])) //if there's no search, exit
      exit;
    
        $keyword = trim($_REQUEST['term']);
        $keyword = mysqli_real_escape_string($db, $keyword);
        $query = "SELECT * FROM animals WHERE english LIKE '%$keyword%' LIMIT 10";
        $result = mysqli_query($db, $query); //Run the Query
    
        $data = array(); //initialize array
    
        if ($result && mysqli_num_rows($result)){
       while($row = mysqli_fetch_assoc($result)){
          $data[] = array(
            'id' => $row['row_id'],
        'label' => $row['english'], //This is the 'live return of the search
        'value' => $row['eng_dir'], //The value returned. Not needed if you're returning the label
        'latin' => $row['latin'] //Another result (you can add more)
           );
        }
         }
        echo json_encode($data);
        flush();
      ?>
    

    然后在 tag-it.js 文件中,您可以选择要推送的内容作为标签:

    if (this.options.availableTags || this.options.tagSource || this.options.autocomplete.source) {
       var autocompleteOptions = {
       select: function(event, ui) {
         that.createTag(ui.item.id); //pushes the ID
     that.createTag(ui.item.value); //pushes the value
         that.createTag(ui.item.label); //pushes the label
         that.createTag(ui.item.latin); //pushes the extra variable
     // Preventing the tag input to be updated with the chosen value.
     return false;
        }
       };
      $.extend(autocompleteOptions, this.options.autocomplete);
    

    上面的代码将根据您的结果返回相同标签的 4 个实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2012-05-08
      • 1970-01-01
      相关资源
      最近更新 更多