简体   繁体   English

我如何在ajax中使用帖子和文件?

[英]how can i use post and files with ajax?

i'd like to know how can i use $_POST and $_FILES using ajax, i'm trying to upload an image and insert a value on my database with post. 我想知道如何使用ajax使用$ _POST和$ _FILES,我试图上传图像并在数据库中插入一个值。

i've tried but it doesn't work. 我已经尝试过了,但是没有用。

index.html index.html

<div class="form-group">
    <label> img </label>
    <input type="file" name="img" id="img" />
    <input type='hidden' id='value' value='<?=$_GET["p"]?>' />
</div>

ajax.js ajax.js

$(document).ready(function() {
    $('#upload').click(function() {
        var value        = $('#value').val();
        var img          = $('#img').val();

        var string= 'value=' + value + '&img=' + img;
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: string,
            dataType: "json",
            success: function(data) {
                var success = data['success'];
                if (success == true) {
                    console.log('success');
                } else {
                    console.log('error');
                }
            }
        }); 
        return false;
    });
});

ajax.php ajax.php

<?php
    if(isset($_POST["value"]) && isset($_FILES["img"])) {
        echo json_encode(array("success" => true));
    } else {
       echo json_encode(array("success" => false));
    }
?>

The best approach is convert image to base64 first. 最好的方法是先将映像转换为base64。 This conversion is done in the change listener. 这种转换是在变更侦听器中完成的。

var files = [];

    $("input[type=file]").change(function(event) {
      $.each(event.target.files, function(index, file) {
        var reader = new FileReader();
        reader.onload = function(event) {  
          object = {};
          object.filename = file.name;
          object.data = event.target.result;
          files.push(object);
        };  
        reader.readAsDataURL(file);
      });
    });

    $("form").submit(function(form) {
      $.each(files, function(index, file) {
        $.ajax({url: "/ajax-upload",
              type: 'POST',
              data: {filename: file.filename, data: file.data},
              success: function(data, status, xhr) {}
        });      
      });
      files = [];
      form.preventDefault();
    });

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

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