如何从“标签框”中获取值

时间:2015-12-27 13:59:38

标签: javascript php jquery

我有“标签框”的以下代码:

HTML:

<div id="tags">
   <input type="text" value="" placeholder="Add a tag" />
</div>

JQuery的:

$(document).ready(function(){
    $('#tags input').on('focusout',function(){
        var txt= this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g,'');
        if(txt) {
            $(this).before('<span class="tag">'+ txt.toLowerCase() +'</span>');
            $(this).before('<input>').attr({
                type: 'hidden',
                name: 'tags[]',
                value: txt.toLowerCase();
        }
        this.value="";
    }).on('keyup',function( e ){
    if(/(188|13)/.test(e.which)) 
        $(this).focusout();
    });
    $('#tags').on('click','.tag',function(){
        $(this).remove(); 
    });
});

我正在使用隐藏的输入向服务器发送标签。单击提交按钮后,表单将我重定向到另一个.php页面。我正在尝试使用var_dump($_POST['tags']),访问php端,但结果是数组(size = 1)   0 =&gt; string''(length = 0)。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您可以使用隐藏的输入向服务器发送标签,这不会在页面上显示任何输入,但会在您提交表单时发送。

$(document).ready(function(){
    $('#tags input').on('focusout',function(){
        var txt= this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g,'');
        if(txt) {
            $(this).before('<span class="tag">'+ txt.toLowerCase() +'</span>');
            $(this).before('<input>').attr({
                type: 'hidden',
                name: 'tags[]',
                value: txt.toLowerCase()
            });
        }
        this.value="";
    }).on('keyup',function( e ){
    if(/(188|13)/.test(e.which)) 
        $(this).focusout();
    });
    $('#tags').on('click','.tag',function(){
        $(this).remove(); 
    });
});

然后在php端访问,如var_dump($_POST['tags']);

答案 1 :(得分:0)

您在服务器端执行此操作。如果PHP是你的服务器端语言,那么是的,你用PHP而不是Javascript。您的PUT user/{user}/changepassword'代码需要具有<input>属性,否则该字段中的数据将无法提交。

如果表单方法是GET,那么PHP脚本应该在$ _GET数组中找到值。如果是POST,那么它将在$ _POST数组中。将其保存到数据库中的实际代码取决于几个因素,包括您是使用普通的PHP或某些MVC框架,您正在使用的数据库,特定的数据库配置和数据结构的名称等。如果您提供更多这些细节,有人可能会用特定代码回答。