简体   繁体   English

如何使用ajax上传图像

[英]how to upload an image using ajax

I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. 我想上传图像而不刷新页面,但是当我点击提交按钮上传图像时,页面仍然刷新。 what is wrong with my ajax code. 我的Ajax代码有什么问题。 This works when am submitting form with plain text but not with image file. 当使用纯文本提交表单而不使用图像文件提交表单时,此方法有效。

test.php test.php

<div class="preview_d_p" id="preview_d_p">
<div class="preview">
    <div class="p_preview">
       <div id="p_p_image"><div id="myimage"></div></div>
    </div>
    <div id="lab"> <label for="photo_upload">upload</label></div>
      <form enctype="multipart/form-data">
      <input type="file" id="photo_upload" name="image_upload">
    <input type="submit" value="save" id="insert_img" onclick="return loadimage()">
    </form>
</div></div>


<script>
function loadimage(){
       var image = documentElement('photo_upload').value;



     $.ajax({
         type:'post',
         url:'profile.php',
         data:{
            image:image

         },
         cache:false,
          success: function(html){

          }

     });

       return false;
    }
</script>

my advice is changing the input to a button (type="button") - I prefer buttons to inputs as they're more easily stylable. 我的建议是将输入更改为按钮(类型=“按钮”)-我更喜欢按钮而不是输入,因为它们更易于样式化。

But you can do something like this to govern submitting data without page refresh: 但是您可以执行以下操作来控制提交数据而无需刷新页面:

HTML EXAMPLE (NOT A COPY OF YOUR HTML): HTML示例(不是您的HTML的副本):

<div id="container">
    <form action="" method="post" id="myForm">
        <input type="text" value="hello world!" />
    </form>

    <!-- what's great about buttons, is that you don't have to place inside the form tags -->
    <button type="button" id="submitBtn">

JS To match JS比赛

$(document).ready(function()
{
    $('#submitBtn').on('click', function()
    {
        //ajaxy stuff
        //will show the success callback function though:
        success: function(res)
                 {
                     $('#container').html(res);   
                 }
    })
});

if your post script returns html then this should work. 如果您的发布脚本返回html,则应该可以。 Let me know if otherwise :) 让我知道是否:)

I solved this problem using formdata to send my image file to server 我使用formdata解决了此问题,将图像文件发送到服务器

$(document).on("submit","form",function(e){
    e.preventDefault();

    var file = $("#product-file-i").val();
    var p = $("#product-upload-f").children("input[name=name]").val();

 $.ajax({
             type:"post",
             url:"profile.php",
             data:new FormData(this),
             contentType:false,
             processData:false,
             cache:false,
             success: function(feedback){
              alert(feedback);

             },
             error: function(){

             }

          });


});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM