AJAX(JavaScript / PHP),FormData不发送

时间:2015-02-28 04:32:56

标签: javascript php jquery ajax

我有一个AJAX调用(使用JQuery),按以下方式设置:

<script type="text/javascript">

var ajax = new XMLHttpRequest();
ajax.open("POST", "testing.php", true);

ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var returnVal = ajax.responseText;

        if(returnVal == "upload_success"){
            $('#display').html("WORKING!");
        }else{
            $('#display').html("NOPE");
        }
    }
}

</script>

我将它与以下测试PHP配对:

<?php

if(isset($_POST['username'])){
    echo "upload_success";
    exit();
}

?>

如果我按以下方式发送AJAX数据:

ajax.send("username=1");

然后一切都很完美。 display div的内部HTML设置为预期的&#34;工作!&#34;

但是如果我发送AJAX 这个方式:

var formData = new FormData();
formData.append("username", 1);
ajax.send(formData);

它将HTML设置为&#34; NOPE&#34; - 意味着未设置帖子变量$_POST['username']

如何在我的PHP函数中检查此特定的AJAX调用?我需要能够区分不同的AJAX调用。

我最终会将文件附加到formData,但我只是先测试一下,因为我之前从未使用过它。

提前谢谢。

编辑1 - HTML

<?php ... PHP from above goes here ... ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="robots" content="noindex, nofollow"/>

<title>Title</title>

<link href="../CSS/styles.css" rel="stylesheet" type="text/css" />
<link href="../CSS/UI/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="../scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="../scripts/UI/jquery-ui.min.js"></script>

<script type="text/javascript"> ... AJAX script from above goes here ... </script>
</head>

<body>

<div id="wrapper">

  <form enctype="multipart/form-data" onsubmit="return false;">
    <input type="file" name="fileField" id="fileField" />
    <br/><br/>
    <input class="button" type="submit" value="Upload"/>
  </form>

  <div id="display"></div>

</div> <!-- End wrapper -->
</body>
</html>

2 个答案:

答案 0 :(得分:1)

我认为您应该使用这种方式使用ajax,

的formdata上传文件

<强>的Javascript

$(document).ready(function(){
      $('#id_of_form').on('submit',function(e){

          e.preventDefault();
    var formdata = new FormData($(this)[0]);      
    $.ajax({
        url: "test.php", 
        type: "POST",    
        data: formdata, 
        contentType: false,
        cache: false,      
        processData:false, 
    success: function(data){
        console.log(data);
        }
      });
  });

PHP(test.php)

if(isset($_FILES)){

    if(isset($_FILES["fileField"]["type"])){

        $validextensions = array("jpeg", "jpg", "png","JPEG","JPG","PNG");
        $temporary = explode(".", $_FILES["add-file"]["name"]);
        $file_extension = end($temporary);
        if ((($_FILES["add-file"]["type"] == "image/png") || ($_FILES["add-file"]["type"] == "image/jpg") || ($_FILES["add-file"]["type"] == "image/jpeg")
        ) && in_array($file_extension, $validextensions)) {

            $sourcePath = $_FILES['add-file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "/photos/".$_FILES['add-file']['name'];
            move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
            /* you can add this taget path to database if required here */
            echo "file uploaded successfuly";
        } 
    }

}

答案 1 :(得分:0)

如果您希望POST表单数据,则需要发送正确的标题信息。

以下是我使用的示例,稍加修改以匹配您的代码示例。

var ajax = new XMLHttpRequest();

var params = "username=test";

ajax.onload = function(aEvent)
{
    if (aEvent.target.responseText == 'upload_success')
    {
        alert('success');
    }
    else
    {
        alert('failed');
    }
};
ajax.onerror = function(aEvent)
{
    alert('failed');
};
ajax.open('POST', 'testing.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.setRequestHeader('Content-length', params.length);
ajax.setRequestHeader('Connection', 'close');
ajax.send(params);

它没有使用任何jQuery,因为没有任何理由使用它。