在javascript

时间:2015-09-25 11:35:57

标签: javascript php html forms

js Fiddle

我在页面上有一个放置区,显示将照片添加到放置区后成功上传到服务器的照片。每张照片都有一个名为“上传”的类,其中包含每个单独的照片。图片上传后,我需要每张照片旁边都有一个输入字段,允许用户为每张照片添加标签。一旦他们键入了将在输入字段中以逗号分隔的标签,他们就可以单击提交。此时函数调用

addTags()
将调用

并根据文件名将标签添加到照片中。 我无法找到最专业的方法,

我正在考虑创建一个包含所有隐藏字段的表单,并使用包含文件名的值添加字段名称。这很容易用ajax获取文件名和标签。请告诉我这样的事情是如何以专业的方式完成的。

这是允许和循环显示上传文件的JS,

 // Initialize the jQuery File Upload plugin
    $('#upload').fileupload({

        // This element will accept file drag/drop uploading
        dropZone: $('#drop'),

        // This function is called when a file is added to the queue;
        // either via the browse button, or via drag/drop:
        add: function (e, data) {

            var tpl = $('<li class="working uploaded"><input type="text" value="0" data-width="48" data-height="48"'+
                ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

        // Append the file name and file size      
            tpl.find('p').text(data.files[0].name)
                         .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

            // Add the HTML to the UL element
            data.context = tpl.appendTo(ul);

            // Initialize the knob plugin
            tpl.find('input').knob();

            // Listen for clicks on the cancel icon
            tpl.find('span').click(function(){

                if(tpl.hasClass('working')){
                    jqXHR.abort();
                }

                tpl.fadeOut(function(){
                    tpl.remove();
                });

            });

            // Automatically upload the file once it is added to the queue
            var jqXHR = data.submit();
        },

因此,为丢弃区域中上传的每个文件返回文件名,如下所示

tpl.find('p').text(data.files[0].name)

现在我如何在这个JS函数中创建表单,为每个上传的文件添加名称到每个隐藏表单字段,并添加一个文本输入字段,允许输入图片的标签。

基本上我正在寻找一种方法来添加这样的表格,

 <form onSubmit="addTags();return false;">
<input type="hidden" name="imgName" value="var imgName" id="imgName">
<input type="text" name="tags" palceholder="add tags seperated by ," id="tags">
<input type="submit" name="login" value="Add Tags" class="submit" id="adTags"/>
                    </form>

addTags()函数

function addTags(){
    $.ajax({
        type: 'POST',
        url: 'data/add_tags.php',
        data: "&tag_type_id=" + $('#tag_type_id').val() + "&tag_target_name=" + $('#tag_target_name').val() +
            "&tag_target_url=" + $('#tag_target_url').val() + "&tags=" + $('#tags').val(),    
                success: function(response){
            console.log(response);
            if(response === 'error'){
                        $('.messageText').empty()
                    $('.messageImage').empty()
                    $('.messageText').append('Please add tags seperated by commas');
                $(".messageImage").append('<img src="images/error.png" height="50" width="50">');
                $('.message').slideDown(400).delay(10000).fadeOut(400)   
            }
            else {
                    $('.messageText').empty()
                    $('.messageImage').empty()
                    $('.messageText').append('Your tags have been added.');
                    $(".messageImage").append('<img src="images/success.png" height="50" width="50">');
                    $('.message').slideDown(400).delay(10000).fadeOut(400)   
            }   
       }
    });
 };

   AJAX makes call to this php function,

<?php
//Include files                 
require_once('../classes/class_login.php');

$tag_type_id = $_POST['tag_type_id'];
$tag_target_name = $_POST['tag_target_name'];
$tag_target_url = $_POST['tag_target_url'];
$tags = $_POST['tags'];

    /*** begin with some validation ***/
    if(!isset($_POST['tag_type_id'], $_POST['tag_target_name'], $_POST['tag_target_url'], $_POST['tags']))
    {
        /*** if no POST is submited ***/
        $msg = 'Please Submit a tag';
        print('error');
    }
    elseif(filter_var($_POST['tag_type_id'], FILTER_VALIDATE_INT, array("min_range"=>1, "max_range"=>100)) == false)
    {
        /*** if tag is too short ***/
        $msg = 'Invalid Tag Type';
                print('error');
    }
    elseif( strlen($_POST['tag_target_url']) == 0 )
    {
        /*** if tag is too long ***/
        $msg = 'Tag target is required';
                print('error');
    }
    elseif( strlen($_POST['tags']) == 0 )
    {
        $msg = 'Tag Required';
                print('error');
    }
    elseif(  strlen($_POST['tag_target_name']) == 0 )
    {
        $msg = 'Tag Name is too short';
                print('error');
    }
    elseif( strlen($_POST['tag_target_name']) > 30 )
    {
        $msg = 'Tag Name is too long!';
                print('error');
    }
    else
    {
        /*** if we are here, all is well ***/

        $tag_type_id = filter_var($_POST['tag_type_id'], FILTER_SANITIZE_NUMBER_INT);
        $tag_target_url = filter_var($_POST['tag_target_url'], FILTER_SANITIZE_STRING);
        $tag_target_name = filter_var($_POST['tag_target_name'], FILTER_SANITIZE_STRING);
        $tags = filter_var($_POST['tags'], FILTER_SANITIZE_STRING);

            addTags($tag_type_id, $tag_target_name, $tag_target_url, $tags);

            $msg = 'Tag Type Added!';
                    print('success');
        }

?>       

php函数在这样的类中定义,

function addTags($tag_type_id, $tag_target_name, $tag_target_url, $tags){

        /*** explode the tag string ***/
            $tag_array = explode(',', $tags);

            /*** loop of the tags array ***/
            foreach( $tag_array as $tag_name )
            {
                /*** insert tag into tags table ***/
                $tag_name = strtolower(trim($tag_name));

                $databaseQuery = "INSERT IGNORE INTO tags (tag_name ) VALUES ('$tag_name')";
                //Execute database query
                executeDatabase($databaseQuery);

                /*** get the tag ID from the db ***/
                $databaseQuery  = "SELECT tag_id FROM tags WHERE tag_name='$tag_name'";
                $result = executeDatabase($databaseQuery);
                $tag_id = mysqli_num_rows($result);

                /*** now insert the target ***/
                $databaseQuery = "INSERT INTO tag_targets
                    (tag_id, tag_target_name, tag_target_url, tag_type_id)
                    VALUES
                    ('$tag_id', '$tag_target_name', '$tag_target_url', '$tag_type_id')";
                executeDatabase($databaseQuery);
            }
}

1 个答案:

答案 0 :(得分:0)

在循环中,您可以使用createElementsetAttributeappendChild创建元素,设置其属性并将其附加到DOM。例如:

var myNewElement= document.createElement("input");
myNewElement.setAttribute("id","new_element_id");
myNewElement.setAttribute("class","new_element_class");
myNewElement.setAttribute("name","new_element_name");
document.getElementById("desired_parent").appendChild(myNewElement);

请注意,有一种替代/补充方法。如果您正在创建许多类似的复杂元素(例如,您有一个'图像描述符'框,其中包含一些文本元素,输入字段,几个div等),您可以在页面上有一个隐藏元素所有这些元素,克隆它,并使用此方法来修改它的一部分并将其放在您想要的位置。