简体   繁体   English

无法通过Ajax将数据发送到php文件

[英]Unable send data to php file via ajax

This is my HTML code.I'm not using <form> 这是我的HTML代码。我没有使用<form>

<input id="sortpicture" type="file" data-id="7" name="sortpic" multiple/>
<button id="upload">Upload</button>

Here is JS 这是JS

jQuery('#upload').on('click', function() {
    var file_data = jQuery('#sortpicture').prop('files')[0];       
    var form_data = new FormData();                  
    form_data.append('file', file_data); 
    form_data.append('id', 7); // ---> If I send this only i'm able to access `id` in php. If include `file` not access id in php file.

    jQuery.ajax({
        url: 'upload.php',   
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'POST',
        success: function(response){        
        },
        error:function(e){
        }
    });

PHP file PHP文件

$name = $_FILES['file']['name'];
//print_r($_FILES);
$id = $_POST['id'];    // Unable to get id.

How can I get id in php file.Any suggestions please. 如何在php文件中获取id 。请提出任何建议。

Based on the documentation, I believe you're close. 根据文档,我相信您已经接近了。 Keep in mind that I have never used the FormData API :) But, if I am interpreting it correctly, it's looking for the "name" attribute. 请记住,我从未使用过FormData API :)但是,如果我正确地解释了它,它会在寻找“名称”属性。

jQuery('#upload').on('click', function() {
    var formData = new FormData(); 
    var inputData = $('this').find('input');
    var fileData = inputData.files[0];       

    formData.append('file', fileData); //wants name attribute here?//
    formData.append('id', 7);

    jQuery.ajax({
        url: 'upload.php',   
        cache: false,
        contentType: false,
        processData: false,
        data: formData,                         
        type: 'POST',
        success: function(response){        
        },
        error:function(e){
        }
    });
});

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

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