无法通过jQuery中的其他参数传递formData [英] Unable to pass formData with other parameters in jQuery

查看:102
本文介绍了无法通过jQuery中的其他参数传递formData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将formData以及其他参数传递给PHP脚本.

I am trying to pass formData along with other parameters to a PHP script.

使用$ .post方法,出现非法调用"错误.所以我放弃了$ .post方法,转而使用了$ .ajax方法.

Using the $.post method, I was getting an 'Illegal Invocation' error. So I abandoned the $.post method and went to $.ajax method.

如下:

$('#uploadBtn').on('click', function()
{
  var formData = new FormData($('#uploadfile')[0]); // the form data is uploaded file
  var booking = $('#bookingNum').val();
  var partner = $('#partnerCode').val();

  var parameters =
  {
    formData:formData,
    booking:booking,
    partner:partner
  } 

  $.ajax({
    url: 'process/customer.php',
    data: parameters,  // <- this may be wrong
    async: false,
    contentType: false,
    processData: false,
    cache: false,
    type: 'POST',
    success: function(data)
    {
      console.log(data);
    },
    error: function(jqHHR, textStatus, errorThrown)
    {
      console.log('fail: ' + errorThrown);
    }
  });
});

在PHP方面,我试图像这样获取参数对象:

On the PHP side, I'm trying to get the parameters object like so:

<?php
if(isset($_POST['parameters']))
{
  echo "Hello";  

  $value = $_POST['parameters'];
  // I can get the other 2 parameters like this
  $company = htmlspecialchars(trim($value['booking']));
  $partner = htmlspecialchars(trim($value['partner']));

  // not sure how to get the uploaded file information      
}
?>

基本上,我正在上传要保存到目录的文件.但是问题是,我无法将任何东西发送到PHP端.我收到此警告:

Basically, I am uploading a file to be saved to a directory. But the problem is, I cannot send anything over to the PHP side. I am getting this warning:

"jquery.js:2 [不推荐使用]不赞成在主线程上使用同步XMLHttpRequest,因为它对最终用户的体验具有不利影响.有关更多帮助,请检查

"jquery.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."

我需要能够将"parameters"对象发送到PHP脚本,然后对其进行处理.

I need to be able to send the 'parameters' object over to the PHP script, then access it for processing.

如何使用$ .ajax方法实现这一目标?那么如何在PHP端一次访问formData?

How can I achieve this using the $.ajax method? Then how do I access the formData once on the PHP side?

推荐答案

参数是您正在POSTing的对象.键值对将基于其属性.尝试访问它们,例如$_POST['formData']$_POST['booking'].

The parameters is the object you are POSTing. the key value pairs will be based on it's properties. Try accessing them like $_POST['formData'] and $_POST['booking'].

还...请重新编写代码以删除async:false ... TBH,这绝对不应该放在jQuery中,这绝对是可怕的.别难过,这是每个新手在首次使用ajax(包括我自己)时尝试的第一件事.您将导致UI线程在整个持续时间内挂起,从而阻止了呼叫期间所有用户的交互.

Also... please rework your code to remove the async:false ... TBH this should never have been put into jQuery and is absolutely terrible. Don't feel bad, it's the first thing every newcomer tries when they first start using ajax, myself included. You're going to cause the UI thread to hang for the duration, preventing all user interaction during the call.

编辑 我没有意识到您首先尝试发布文件,因此这并不是一个完整的答案,因为我认为您没有正确访问它.但是,此答案的重要部分是没有$_POSTparameters索引(这就是为什么连您的回声"hello"都不会回来的原因.)

EDIT I didn't realize you are trying to post a file at first, so this is not a complete answer as I don't think you are accessing it correctly. But The important part of this answer is that there is no parameters index of $_POST (which is why not even your echo "hello" is coming back).

如果您发布的对象看起来像

if you POST an object that looks like

{
  key1 : "value1",
  key2 : "value2"
}

他们将以

$_POST['key1'];//"value1";
$_POST['key2'];//"value2";

注意,发布到服务器的文件通常位于$ _FILES超全局文件中. (不知道AJAX是否会更改它,但我想不会)

important to note, files posted to the server are typically found in the $_FILES superglobal. (don't know if AJAX changes that, but I imagine not)

EDIT2

将两者结合起来……这是一般的想法.使您的html + JS看起来像...

Combining the two... this is the general idea. Make your html + JS look like...

$('#form').on('submit', function()
{
  var form_data = new FormData();

  form_data.append("file", document.getElementById('fileInput').files[0]);
  var booking = $('#bookingNum').val();
  var partner = $('#partnerCode').val();

  form_data.append("booking ",booking); 
  form_data.append("partner",partner);  

  $.ajax({
    url: 'process/customer.php',
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data)
    {
      console.log(data);
    },
    error: function(jqHHR, textStatus, errorThrown)
    {
      console.log('fail: ' + errorThrown);
    }
  });
  
  return false;//prevent default form submission
});

<form id='form'>
  <input type='file' id='fileInput' />
  <label for='bookingNum'>Booking Num: </label>
  <input type='text' id='bookingNum' name='bookingNum' />
  <label for='partnerCode'>Partner Code:</label>
  <input type='text' id='partnerCode' name='partnerCode' />
  <button id='uploadBtn'>Submit</button>
</form>

并尝试使用

<?php 
if($_POST['bookingNum']){
    var_dump($_POST['bookingNum']);
}
if($_POST['partnerCode']){
    var_dump($_POST['partnerCode']);
}
if($_FILES['file']){
    var_dump($_FILES['file']);
}

这篇关于无法通过jQuery中的其他参数传递formData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆