ajax文件无法将文件字段值传递给php文件

时间:2013-05-22 03:18:20

标签: php ajax forms

我的ajax文件有问题。 ajax文件不能与php表单一起使用。 当我运行代码时,它显示错误file_get_content错误,文件名为空。

php代码正常运行。但是ajax文件无法传输文件字段值。 因此该文件无法附加邮件。

它显示错误:文件名为空

plz帮助我通过ajax文件传递文件字段值。

<div>
<form  method="post" enctype="multipart/form-data" name="form1" id="form1"     action="contactus.php" onsubmit="xmlhttpPost('contactus.php', 'form1', 'Myresult', ''); return false;">
Name:<input name="name1" type="text"   value="" />
Address:<input name="address1" type="text"  value="" /> 
Phone:<input name="phone1" type="text" value=""/>
Email: <input name="email1" type="text" value="" />
File:<input name="file" type="file" size="35" id="file" />
Links:<input name="links1" type="text" value="" />
Subject:<input name="subject1" type="text" value="" />
Location:<select name="location">
              <option value="" selected="selected">--Select--</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

Comments:<textarea name="comment1"  ></textarea>
<input name="submit" id="submit" type="submit"/>   
<div id="Myresult"></div>
</form>
</div>

php form(contactus.php)

<?php
if(isset($_POST['submit']))
{

 $name=$_POST['name1'];
$address=$_POST['address1'];
$phone=$_POST['phone1'];
$email=$_POST['email1'];
$subject=$_POST['subject1'];
$location=$_POST['location'];
$comment=$_POST['comment1'];
$links=$_POST['links1'];

$to='mail@mail.com';

 $message .= "\nName: ".$name."\n\n";
 $message .= "Address: ".$address."\n\n";
 $message .= "Phone: ".$phone."\n\n";
 $message .= "Email: ".$email."\n\n";
  $message .= "Links: ".$links."\n\n";
  $message .= "Location: ".$location."\n\n";
  $message .= "Comments:\n\n ".$comment."\n";



$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
    $filename = $_FILES['file']['name'];
    $filetype = $_FILES['file']['type'];        
    $boundary =md5(date('r', time())); 

$headers = "From: $name <$email>\r\nReply-To: $name <$email>";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";


$message="This is a multi-part message in MIME format.

  --_1_$boundary
 Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

 --_2_$boundary
 Content-Type: text/plain; charset=\"iso-8859-1\"
 Content-Transfer-Encoding: 7bit

 $message

 --_2_$boundary--
 --_1_$boundary
 Content-Type: $filetype; name=\"$filename\" 
 Content-Transfer-Encoding: base64 
 Content-Disposition: attachment 

 $attachment

 --_1_$boundary--";

 mail($to,$subject,$message,$headers);

 print 'Thanks, your message sent!';

 }

 ?>

ajax.js

function xmlhttpPost(strURL, formname, responsediv, responsemsg) {
    var xmlHttpReq = false;
    var self = this;
    // Xhr per Mozilla/Safari/Ie7
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // per tutte le altre versioni di IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function () {
        if (self.xmlHttpReq.readyState == 4) {
            // Quando pronta, visualizzo la risposta del form
            updatepage(self.xmlHttpReq.responseText, responsediv);
        } else {
            // In attesa della risposta del form visualizzo il msg di attesa
            updatepage(responsemsg, responsediv);
        }
    }
    self.xmlHttpReq.send(getquerystring(formname));
}

function getquerystring(formname) {
    var form = document.forms[formname];
    var qstr = "";

    function GetElemValue(name, value) {
        qstr += (qstr.length > 0 ? "&" : "") + escape(name).replace(/\+/g, "%2B") + "=" + escape(value ? value : "").replace(/\+/g, "%2B");
        //+ escape(value ? value : "").replace(/\n/g, "%0D");
    }

    var elemArray = form.elements;
    for (var i = 0; i < elemArray.length; i++) {
        var element = elemArray[i];
        var elemType = element.type.toUpperCase();
        var elemName = element.name;
        if (elemName) {
            if (elemType == "TEXT" || elemType == "TEXTAREA" || elemType == "PASSWORD" || elemType == "BUTTON" || elemType == "RESET" || elemType == "SUBMIT" || elemType == "FILE" || elemType == "IMAGE" || elemType == "HIDDEN")

            GetElemValue(elemName, element.value);
            else if (elemType == "CHECKBOX" && element.checked) GetElemValue(elemName,
            element.value ? element.value : "On");
            else if (elemType == "RADIO" && element.checked) GetElemValue(elemName, element.value);
            else if (elemType.indexOf("SELECT") != -1)

            for (var j = 0; j < element.options.length; j++) {
                var option = element.options[j];
                if (option.selected) GetElemValue(elemName,
                option.value ? option.value : option.text);
            }
        }
    }
    return qstr;
}

function updatepage(str, responsediv) {
    document.getElementById(responsediv).innerHTML = str;
}

1 个答案:

答案 0 :(得分:1)

无法重现您的错误。试试这个:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['submit1'])) {

        $name     = $_POST['name1'];
        $address  = $_POST['address1'];
        $phone    = $_POST['phone1'];
        $email    = $_POST['email1'];
        $subject  = $_POST['subject1'];
        $location = $_POST['location'];
        $comment  = $_POST['comment1'];
        $links    = $_POST['links1'];

        $to = 'mail@mail.com';

        $message .= "\nName: " . $name . "\n\n";
        $message .= "Address: " . $address . "\n\n";
        $message .= "Phone: " . $phone . "\n\n";
        $message .= "Email: " . $email . "\n\n";
        $message .= "Links: " . $links . "\n\n";
        $message .= "Location: " . $location . "\n\n";
        $message .= "Comments:\n\n " . $comment . "\n"; 

        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename   = $_FILES['file']['name'];
        $filetype   = $_FILES['file']['type'];
        $boundary   = md5(date('r', time()));

        $headers = "From: $name <$email>\r\nReply-To: $name <$email>";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message = "This is a multi-part message in MIME format.

          --_1_$boundary
         Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

         --_2_$boundary
         Content-Type: text/plain; charset=\"iso-8859-1\"
         Content-Transfer-Encoding: 7bit

         $message

         --_2_$boundary--
         --_1_$boundary
         Content-Type: $filetype; name=\"$filename\" 
         Content-Transfer-Encoding: base64 
         Content-Disposition: attachment 

         $attachment

         --_1_$boundary--";

        mail($to, $subject, $message, $headers);

        print 'Thanks, your message sent!';
        exit;
    }

    print 'Some error';
    exit;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <script>
        function xmlhttpPost(strURL, formname, responsediv, responsemsg) {
            var xmlHttpReq = false;
            var self = this;
            if (window.XMLHttpRequest) {
                self.xmlHttpReq = new XMLHttpRequest()
            } else if (window.ActiveXObject) {
                self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP")
            }
            self.xmlHttpReq.open('POST', strURL, true);
            self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            self.xmlHttpReq.onreadystatechange = function () {
                if (self.xmlHttpReq.readyState == 4) {
                    updatepage(self.xmlHttpReq.responseText, responsediv)
                } else {
                    updatepage(responsemsg, responsediv)
                }
            }
            self.xmlHttpReq.send(getquerystring(formname))
        }
        function getquerystring(formname) {
            var form = document.forms[formname];
            var qstr = "";

            function GetElemValue(name, value) {
                qstr += (qstr.length > 0 ? "&" : "") + escape(name).replace(/\+/g, "%2B") + "=" + escape(value ? value : "").replace(/\+/g, "%2B")
            }
            var elemArray = form.elements;
            for (var i = 0; i < elemArray.length; i++) {
                var element = elemArray[i];
                var elemType = element.type.toUpperCase();
                var elemName = element.name;
                if (elemName) {
                    if (elemType == "TEXT" || elemType == "TEXTAREA" || elemType == "PASSWORD" || elemType == "BUTTON" || elemType == "RESET" || elemType == "SUBMIT" || elemType == "FILE" || elemType == "IMAGE" || elemType == "HIDDEN") GetElemValue(elemName, element.value);
                    else if (elemType == "CHECKBOX" && element.checked) GetElemValue(elemName, element.value ? element.value : "On");
                    else if (elemType == "RADIO" && element.checked) GetElemValue(elemName, element.value);
                    else if (elemType.indexOf("SELECT") != -1) for (var j = 0; j < element.options.length; j++) {
                            var option = element.options[j];
                            if (option.selected) GetElemValue(elemName, option.value ? option.value : option.text)
                    }
                }
            }
            return qstr
        }
        function updatepage(str, responsediv) {
            document.getElementById(responsediv).innerHTML = str
        }
        </script>
    </head>
    <body>
        <div>
            <form  method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="xmlhttpPost('', 'form1', 'Myresult', ''); return false;">
                <input type="submit" name="submit1" value="Submit">
                <div id="Myresult"></div>
            </form>
        </div>
    </body>
</html>