简体   繁体   中英

jQuery using $.post to upload file

I need to send POST data by jQuery to my PHP server. And this is what I'm currently receiving ( which is what I want ):

client_id: 55
client_name: 'Josh'
age: '35'
extra: array(0) -> array(['preview'] -> true, ['lookup'] -> false)

And to achieve this I have the following code:

var elements    = [];
var listOfExtra = []

listOfExtra.push({'preview': true, 'lookup': false});

elements['client_id']   = 55;
elements['client_name'] = 'Josh';
elements['age']         = 35;
elements['extra']       = listOfExtra;

$.post(url, $.extend({}, elements));

But now I also need to send a file the user has upload, so by doing this:

elements['file'] = event.target.files[0];

I receive the message Illegal invocation in javascript

Since this didn't work I tried to implement a formData() :

var formData = new FormData();

formData.append('client_id', 55);
formData.append('client_name', 'Josh');
formData.append('age', 35);
formData.append('extra', listOfExtra);
formData.append('file', event.target.files[0]);

$.ajax(
{
    url: url
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false
});

What happens is that now the extra is an [object][object] , which is OK, so I just need to stringify it.

formData.append('extra', JSON.stringify(listOfExtra));

The problem now is that I have lots of code that uses $_POST['extra'][0]['preview'] (for example) and now I need to decode all of it before and use lots of conditions, like:

$extra = isset(json_decode($_POST['extra'])[0]['preview']);

if($extra != null)
   $extraContent = json_decode($_POST['extra'])[0];

$preview = (isset($extraContent) ? $extraContent->preview : $extra[$_POST['extra'][0]['preview']);

Is there any way by using formData() or $.post I can keep the values sent from javascript to PHP like I want and send the file?

An easy way is, to not use jQuery for that but simply

var xhr = new XMLHttpRequest();
xhr.send(formData);

It should do all the right things, but works only in modern browsers (don't know if you need the older ones too). For compatibility look at http://caniuse.com/#feat=xhr2

Solved .

I converted the JSON values decoded into a normal $_POST again.

$extraContent = json_decode($_POST['extra'])[0];

foreach($extraContent as $key => $extra)
   $_POST[$key] = $extra;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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