简体   繁体   English

jQuery Ajax发布文件

[英]jQuery Ajax post file

I try to post an uploaded file via ajax to php. 我尝试通过ajax将上传的文件发布到php。

HTML : HTML

<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data"> 
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />

JS JS

$("#uploadForm").submit(function () {
    var formData = new FormData();
    formData.append( 'csv',  $( '#csv' )[0].files[0] ); 
    formData.append( 'name', $( '#name'));
    jQuery.ajax({
        url: "../lib/import.php",
        data: formData,
        type: "POST",
        success: alert('erfolgreich'),
        error: alert('Fehler'),
        cache: false,
        contentType: false,
        mimeType: 'multipart/form-data',
        processData: false
    });     
});

and then i try to get the form data in PHP: 然后我尝试在PHP中获取表单数据:

$_FILES['csv']
$_POST['name']

But the Ajax call completes with success and error... I'm confused... The PHP file will not executed correctly... 但是Ajax调用以成功和错误来完成...我很困惑... PHP文件将无法正确执行...

Thanks for your help! 谢谢你的帮助!

You aren't assigning functions to success or error . 您不是要为successerror分配功能。

You are calling the alert function immediately and then assigning its return value. 您正在立即 调用警报功能,然后分配其返回值。

You need to create new functions to assign to success and error . 您需要创建新功能以分配给successerror

success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },

You are also calling the function as a submit handler, but aren't preventing the normal form submission. 您还以提交处理程序的形式调用该函数,但并没有阻止正常表单的提交。 Consequently, the browser will load a new page before processing the response to the Ajax request. 因此,浏览器将在处理对Ajax请求的响应之前加载新页面。

$("#uploadForm").submit(function (event) {
    event.preventDefault();

Try restructuring your AJAX call with your success and failure code like this: 尝试使用以下成功和失败代码重构AJAX调用:

$.post('../lib/import.php', formData).done(function() {
    console.log('done');
}).fail(function() {
    console.log('error');
});

See http://api.jquery.com/jquery.post/ for more examples. 有关更多示例,请参见http://api.jquery.com/jquery.post/

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

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