如何使用相同的id但不同的内容进行更新

How can I do update with using same id but different content?

本文关键字:更新 何使用 id      更新时间:2023-09-26

目前,我正在处理一个为图像文件输入的表单。浏览完图片后上传,我会得到图片的id。这是我的POST代码。

$("#smallpicture_id").change(function () {
    displayAndShowImage(this,'#smallimg','#smallimg'); 
});
$("#largepicture_id").change(function () {
    displayAndShowImage(this,'#largeimg','#largeimg');
});
function displayAndShowImage(input,targetHtmlElementName) {
    if (input.files && input.files[0]) {
        var files = input.files;
        var reader = new FileReader();
        reader.onload = function (e) {
            $(targetHtmlElementName).attr('src', 'images/uploading.gif');
            var formData = new FormData();
            formData.append('userfile',files[0],files[0].name);
            createImage(
                config,
                formData,
                {
                    onSuccess : function(data) {
                        $(targetHtmlElementName).attr('src', e.target.result);
                        $.cookie(input.id, data);
                        console.log("Image has been save - Received ID: " + data + " saved in the cookie " + input.id);
                    },
                    onError : function(jqXHR, status) {
                        $(targetHtmlElementName).attr('src', 'images/img-error.png');
                        console.log("ERROR " + jqXHR.responseText + "'r'nstatus = " + status);
                    }
                }
            );
        }
        reader.readAsDataURL(files[0]);
    }
}

Ajax

function createImage(cfg,formData,callbacks) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', cfg.url + "/image/", true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            // File(s) uploaded.
            callbacks.onSuccess(xhr.responseText.trim());
        } else {
            callbacks.onError(xhr);
        }
    };
    xhr.send(formData);
}

我的问题是,如何使用与图像相同的id更新/删除图像。我已经可以进行POST和GET,但我仍然不知道如何更新和删除。

您可以在FormData查询标识符和ID中附加两个字符串(仅在更新和删除的情况下),如

formData.append('queryType', 'DELETE')
formData.append('imageID', input.id)

在服务器端代码(你已经添加了保存新图像的代码)上,你必须添加类似的条件

<?php
$identifier=$_POST['queryType'];
if($identifier=="NEW") {
    //save file with new ID and return ID
} elseif ($identifier=="UPDATE")
    //update Image Data ($_FILE) with ID appended in formdata
} elseif ($identifier=="DELETE")
    //Delete existing image at ID specified
}
?>

希望这能有所帮助。

您可以为每个上传进程指定具有相同id的元素特定类名,然后运行displayAndShowImage函数,只为具有"update this"类名的元素指定类名。

$("#smallpicture_id").change(function () {
    $(this).addClass("update-this"); // add update-this class
    $(".update-this").not($(this)).removeClass("update-this"); // remove all update-this classnames from all other ones
    // then run your function for only element which has update-this classname
    displayAndShowImage(this,'.update-this'); 
});