用js向php发送请求

时间:2016-01-25 17:27:01

标签: javascript php xmlhttprequest

我使用php和javascript创建一个简单的上传文件系统但是当我想发送输入[text]时,值数据没有发送

这是我的HTML代码:

    <div id="upload_video">
<div id="close_btupvid">×</div>
<div class="upload_video">
<div id="statu"></div>
<h2>Upload Video</h2>
  <div id="status"></div>
<form enctype="multipart/form-data" method="post">
<input type="file" name="up_vid" id="up_vid"/>
<div class="upload_v_icon"></div>
<div class="video_info">
<input type="text" name="video_title" placeholder="Video Title" id="video_title"/>
<input type="text" name="tags" placeholder="Tags (funny,9gag,cool,amazing ...)"/>
<textarea name="description" placeholder="video description"></textarea>
</div>
<div class="bg_upload">
<p>When you upload this video your agree with <a href="">Terms</a> of service.</p>
<input type="button" name="upload_v_bt" value="Begin Upload"  onclick="uploadvideo()"/>
</div>
</form>
</div>
</div>

这是我的js代码:

<script>
function _(el){
    return document.getElementById(el);
}
function uploadvideo(){
    var video_file = _("up_vid").files[0];
    //alert(video_file.name+" | "+video_file.size+" | "+video_file.type);
    var formvideo = new FormData();
    formvideo.append("up_vid", video_file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    if((video_file.type == "video/mp4") || (video_file.type == "video/flv")) {
    var video_titl = document.getElementById("video_title").value;
    var vars = "video_title="+video_titl;
alert(video_titl);
    ajax.open("POST", "functions/video.php",true);
    ajax.send(formvideo);
     // Send the data to PHP now... and wait for response to update the status div
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    ajax.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
            var return_data = ajax.responseText;
            document.getElementById("statu").innerHTML = return_data;
        }
    }
    ajax.send(vars); // Actually execute the request
    document.getElementById("statu").innerHTML = "<center><i class='fa fa-spinner fa-pulse fa-x fa-fw' style='color:#000; position:relative; top:6px;'></i></center>";

    }else{
var divc = document.createElement("div");
divc.innerHTML = "The file must be Extensions (.jpg,.png)";
divc.setAttribute('id', 'error'); // and make sure myclass has some styles in css
//div.setAttribute('class', 'container animated fadeInDown'); // and make sure myclass has some styles in css
document.getElementById('upload_video').appendChild(divc);  
}
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("statu").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("statu").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("statu").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("statu").innerHTML = "Upload Aborted";
}
</script>
这是我的PHP代码:

$fileName = $_FILES["up_vid"]["name"]; // The file name
$fileTmpLoc = $_FILES["up_vid"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["up_vid"]["type"]; // The type of file it is
$fileSize = $_FILES["up_vid"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["up_vid"]["error"]; // 0 for false... and 1 for true
$upload = move_uploaded_file ($fileTmpLoc,'../'.$fileName);
echo $_POST['video_title'];

请帮我解决这个问题

2 个答案:

答案 0 :(得分:1)

首先,更正脚本标记

<script type="text/javascript"></script>

在您的脚本上方,包含JQuery

<script type="text/javascript" src="jquery-2.1.4.min.js"></script>

我不确定'_()'的命名法,但与jQuery类似,您可以使用以下$(&lt; ELEMENT_NAME&gt;)模式来避免'document.getElementById'。见下文

$("loaded_n_total").html("<p>Uploaded "+event.loaded+" bytes of "+event.total + "</p>");
var percent = (event.loaded / event.total) * 100;
$("progressBar").value = Math.round(percent);
$("statu").html("<p>" +Math.round(percent)+"% uploaded... please wait</p>")

您也应该将点击处理程序移动到脚本中,并在输入

上设置类选择器名称
<input class="uploadVidSubmit" type="Button" value="click me"></input>

和js

//in your js file
$("uploadVidSubmit").click(function(e) 
{
    uploadVideo();
});

最后,确保脚本位于文档的“head”标记中,并作为单独的JS文件包含在内

<script type="text/javascript" src="myclickhandler.js"></script>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>

您正在发送'POST',但您正在指定'application / x-url-encoded ...' 确保mime类型正确。要上传视频,我的.htaccess已

AddType video/avi .avi
AddType video/quicktime .mov
AddType video/mpeg .mpeg .mpg
AddType video/mp4 .mp4

最后,检查Charles以查看点击(或不点击)时是否有传出请求

答案 1 :(得分:0)

我的声誉不足以评论,因为我是一个失败者。这应该是评论,而不是答案。

我注意到您要发送请求两次,一次是使用表单视频,一次是使用标题。这会产生影响吗?

发送请求时,您可以完全发送普通的js对象。您是否尝试将标题和视频存储在对象上并一次性发送?

Php可以使用全局post变量识别该对象。

所以

this._length

编辑:以这种方式发送对象适用于IE8及更高版本以及大多数其他浏览器