ajax请求返回一个空字符串作为响应

时间:2016-08-14 06:35:22

标签: javascript php ajax

这里我试图通过ajax使用post方法提交表单。我使用formData对象来收集和发送表单。但是当我从目标页面回显一个字段值时,它返回一个空字符串。这意味着表单不是提交。在控制台中,我收到状态代码200. formdata对象也获得了所有输入。可能是什么原因?

<form action='home.php' method='POST' id='myform' enctype='multipart/form-data'>
name : <input type='text' name='myname'  id='name_select'>
file : <input type='file' name='myfile' id='file_select' >
<input type='submit' value='form submit' id='submitbtn'>
</form>

<script>
var name=document.getElementById('name_select');
var file=document.getElementById('file_select');
var sub=document.getElementById('submitbtn');
var form=document.getElementById('myform');

sub.addEventListener('click',function(event){
     event.preventDefault();
     sub.value='uploading...';
     var xhr=new XMLHttpRequest();
     var formdata=new FormData();
     var files=file.files[0];

     var inputs=document.getElementsByTagName('input');
     for(i=0;i<inputs.length;i++){

         if(!inputs[i].disabled){

             if(inputs[i].type=='file'){

                formdata.append(inputs[i].name,files,files.name);
             }else{

                formdata.append(inputs[i].name,inputs[i].value);
             }
         }
     }

     xhr.onreadystatechange=function (){

         if(xhr.readyState==4){

             if(xhr.status==200){

                 console.log('form submitted');
                 alert((xhr.response));
                 sub.value='upload';

             }else{
                 console.log('there is a problem');
             }
         }
     }
     xhr.open('POST','home.php',true);
     xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xhr.send(formdata);
});
</script>

home.php:

<?php


      echo $_POST['myname'];

?>

2 个答案:

答案 0 :(得分:0)

这可能发生在多部分表单数据中。 通常,您可以使用jquery表单插件简化ajax。 http://malsup.com/jquery/form/

$('#myForm').ajaxForm();

这个插件基于jquery ajax,主要支持jquery ajax中的所有内容(beforeSend,success,fail,...)。

答案 1 :(得分:0)

this so post solved my problem. 问题在于以下一行

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

因为我有二进制数据发送到服务器所以我有多部分/表格数据作为enctype形式elemet.application / x-www-form-urlencoded用于向服务器发送查询字符串。另一方面multipart / form-data用于向服务器发送大型二进制数据。因此,省略上述行解决了我的问题。

相关问题