简体   繁体   English

JQuery 的 .load 函数不会将变量传递给我的 PHP 文件

[英]JQuery's .load function won't pass variable to my PHP file

I'm aware that this is possible using JQuery's ajax functions but I'm specifically wanting to try do this using JQuery's .load() function.我知道使用 JQuery 的 ajax 函数可以做到这一点,但我特别想尝试使用 JQuery 的.load()函数来做到这一点。

Here's my code:这是我的代码:

HTML: HTML:

<form class="form" action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="csv-file">
    <p class="upload-button">Upload</p>
    <p class="upload-output"></p>
</form>

Javascript: Javascript:

$('.upload-button').click(function() {
    var formData = $('.form').serializeArray();
    $('.upload-output').load('upload.php', formData);
});

When I click on the upload-button the form is serialized and sent to my PHP file called upload.php .当我点击upload-button ,表单被序列化并发送到我的名为upload.php PHP 文件中。 This is the contents of upload.php - I'm currently just checking to see if it recieves the file at all:这是upload.php的内容——我目前只是检查它是否完全收到文件:

if(isset($_FILES['csv-file'])){
    echo 'found file';
} else echo 'no file';

All of this looks fine but for some reason it returns no file every time and I'm not sure why.所有这些看起来都很好,但由于某种原因,它每次都no file返回no file ,我不确定为什么。

I've tried different input types like a text field, textarea and they all work but whenever I try to pass an input with type file it doesn't work.我尝试了不同的输入类型,如text字段、 textarea ,它们都可以工作,但是每当我尝试使用类型file传递输入时,它都不起作用。 Why is this?这是为什么? and how can I get the file through to my PHP file using .load() ?以及如何使用.load()将文件传递到我的 PHP 文件? Is it even possible?甚至有可能吗?

Actually, you can't upload files with Ajax that way because .serialize() only gives you the file names.实际上,您不能以这种方式使用 Ajax 上传文件,因为 .serialize() 只为您提供文件名。

Use FormData:使用表单数据:

$('.upload-button').click(function() {
var formData = new FormData($('form')[0]);
$('.upload-output').load('upload.php', formData); });

Also see: Sending multipart/formdata with jQuery.ajax另请参阅: 使用 jQuery.ajax 发送多部分/表单数据

And: How can I upload files asynchronously?以及: 如何异步上传文件?

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

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