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() 関数の script タグの行:

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 を使用してファイルをアップロードすることはできません。非表示の iframe を使用できる AJAX のような方法でファイルをアップロードする必要がある場合は、ターゲット属性を 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 に答える