【问题标题】:Pass image on ajax call and read with php [duplicate]在ajax调用上传递图像并用php读取[重复]
【发布时间】:2021-02-24 11:04:38
【问题描述】:

我创建了一个输入值的表单,然后 jQuery 将读取该表单。此时,jQuery 将对 PHP 文件进行 ajax 调用,该文件必须将文章上传到 MySQL(它已经这样做了)。问题是我找不到将图像的 tmp 传递给 PHP 以使其读取的方法。

第一个代码:表单

 <form class="form">
  <input type="text" id="titolo" placeholder="Titolo" name="post_title" />
  <input type="text" id="autore" placeholder="Autore" name="post_author"  />
  <input type="date" id="data" name="post_date" />
  <select id="categoria" name="category">
    // code php from mysql to select category               
  </select>
  <textarea id="article" name="post_content" rows="10" cols="30"></textarea><br/>             
  <label for="anteprima">Seleziona l'immagine di anteprima:</label><br/>
  <input type="file" accept="image/*" id="anteprima" name="post_image"/><br/>
  <input type="button" value="Upload Articolo" name="submit" class="invia" />
   <div id="public_article"></div>
 </form>

读取对象 jQuery:

$(".invia").click(function(e){ 
  e.preventDefault();
  var v1 = $('#titolo').val();
  var v2 = $('#autore').val();
  var v3 = $('#data').val();
  var v4 = $('#categoria').val();
  var v5 = $('#article').val();
  var v6 = $('#anteprima');

  // here control of the value if it's ok go to the $.post

 $.post("(//here the name of file php)", {titolo: v1, autore: v2 , date: v3, categoria: v4, rif_testo: 
 v5, rif_immagine: v6, cache:false})
        .done(function(dataResult){
            $("#public_article").html(dataResult);
        })
        .fail(function() {
            $("#public_article").html("error");
        }); 

});

我无法将照片发送到 PHP 文件并通过$_FILES 恢复它。

【问题讨论】:

    标签: php ajax call


    【解决方案1】:

    您可以为此使用 FormData:

    var formData = new FormData($(.form)[0]);
    
    
    // now send it not using post but using ajax
        $.ajax({
            url: '//here the name of file php',
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    

    在 PHP 中,您可以像处理普通表单一样处理它。

    【讨论】:

    • 我不能使用 $.post 代替 $ajax 的快捷方式?
    • 据我所知,您不能为此使用 $.post,因为它们是具有不同参数的 2 个不同函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2014-11-17
    • 2014-08-18
    • 1970-01-01
    • 2016-03-29
    • 2015-04-23
    • 2015-05-29
    相关资源
    最近更新 更多