0

我有一个带有这样的表单的 HTML:

<html>

<head>
  <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>

<body>
  <form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
    Your Photo: <input id="thefile" type="file" name="photo" size="25" />
    <input type="button" name="submit" value="Submit" onclick="submitform();"/>
  </form>
</body>

<script>

  function submitform()
  {
    data = $('*').serialize();

    $.post(
      'http://localhost/banksoal/1.0.0/accept-file.php',
      data
    );
  }

</script>

</html>

和这样的 .php 脚本:

        <?php
  //if they DID upload a file...
  if($_FILES['photo']['name'])
  {
    print_r($_FILES['photo']);
    $message = 'default message';

    //if no errors...
    if(!$_FILES['photo']['error'])
    {
      //now is the time to modify the future file name and validate the file
      $new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
      if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
      {
        $valid_file = false;
        $message = 'Oops!  Your file\'s size is to large.';
      }
      else
      {
        $valid_file = true;
      }

      //if the file has passed the test
      if($valid_file)
      {
        //move it to where we want it to be
        move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
        $message = 'Congratulations!  Your file was accepted.';
      }
    }
    //if there is an error...
    else
    {
      //set that to be the returned message
      $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
    }
  }

  var_dump($message);
?>

问题:在 submitform() 函数中,在该行的脚本标记中:

data = $('*').serialize();

为什么我得到空结果?代码有什么问题?

谢谢

4

4 回答 4

1

改变这个

   data = $('*').serialize();

 data = $('theform').serialize();

并改变这个

   <form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">

 <form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
于 2013-01-17T11:27:41.807 回答
0

试一试这里提到的: http ://api.jquery.com/serialize/

$('form').submit(function() {
  console.log($(this).serialize());
  return false;
});
于 2013-01-17T11:17:44.920 回答
0

你也可以使用

echo json_encode($data);

http://php.net/manual/en/function.json-encode.php

于 2013-01-17T11:17:52.947 回答
0

您不能使用 Ajax 上传文件,如果您必须以类似 AJAX 的方式上传文件,您可以使用隐藏的 iframe,将 target 属性设置为 iframe 并获取 iframe 的内容以了解请求是否失败

这是我通常为此目的所做的,创建一个隐藏的 iframe,它将成为表单的目标,如下所示:

<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>

在 processResult 中,您可以通过以下方式获取 iframe 的内容:

$(results).html();

这样当 iframe 加载完成时会自动触发通知请求完成的功能

于 2013-01-17T11:22:30.247 回答