【问题标题】:How to upload images when clicking on a div, not submit button单击div而不是提交按钮时如何上传图像
【发布时间】:2023-03-30 05:34:01
【问题描述】:

我之前有代码允许:当用户单击提交 div 时,contenteditable div 中的文本将使用 Jquery 传递给 upload.php,插入数据库然后立即返回。现在我正在尝试添加也可以处理图像的功能。 IE。上传到upload.php,插入mysql数据库,存储后立即显示。如何修改下面的代码来实现这一点?当我进行研究时,发布的图像是由我不想要的表单提交按钮处理的。

HTML 和 CSS

<html>
<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
  <div id="topic_content_input" contenteditable="true"></div>
  <input multiple class="fileInput" type="file" id="files" name="files[]"/>
  <br>
  <div id="submit" > click me to pass the photo to upload.php</div>
  <div name="topicreturn"></div>
</body>
</html>

<script>
$(function(){
        $("#submit").click(function(){

            var txtContent = $("#topic_content_input").text();
                if(txtContent){

                    $.post("upload.php", {txtContent:txtContent}, function(result){
                        $("div[name=topicreturn]").prepend(result);
                        $("#topic_content_input").text('');
                    });
                 }
})
})

</script>

<style>
#topic_content_input{
    height: 60px;
    width:350px;
    border:1px solid blue;
}
#submit{
    background-color: #ffcc99;
    display:inline-block;
    padding:5px;
    border-radius: 3px;
    cursor:pointer;
}
</style>

PHP 文件(上传.php)

<?php
require('connect.php');


$content=$_POST["txtContent"];

$sql="insert into topics (content) VALUES ('".$content."')";
        $result=mysqli_query($conn,$sql);
        if($result){
            echo $content;
        }
        else{
            echo $content;

        }

?>

【问题讨论】:

标签: javascript php jquery ajax upload


【解决方案1】:

表单提交()方法

submit() 方法提交表单(与单击提交按钮相同)。

document.getElementById("myForm").submit();

所以,你的代码可能是

<form id="myForm" action="form_action.asp">
<div id="topic_content_input" contenteditable="true"></div>
  <input multiple class="fileInput" type="file" id="files" name="files[]"/>
  <br>
  <div id="submit" onClick="subForm();"> click me to pass the photo to upload.php</div>
  <div name="topicreturn"></div>
</form>

<script>
function subForm() {
    document.getElementById("myForm").submit();
}
</script>

【讨论】:

  • 您能帮忙提供一些有关 php 文件的详细信息,以便我测试它吗?
  • 为什么要提交?
【解决方案2】:

jquery中可以使用div id监听点击

  $(".business-bottom-content").click(
    function()
    {
       var txtContent = $("#topic_content_input").text();
            if(txtContent){

                $.post("upload.php", {txtContent:txtContent}, function(result){
                    $("div[name=topicreturn]").prepend(result);
                    $("#topic_content_input").text('');
                });
             }
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 2018-03-28
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多