簡體   English   中英

即使是POST方法,Ajax也充當GET方法

[英]Ajax acting as GET method even though is POST method

您好,我在用Javascript和PHP(Ajax非jquery)編碼時遇到問題。 我試圖通過Ajax上傳文件,並在PHP中處理它。

這是我的代碼:

的index.html

<html>
<head>
<title>PHP AJAX Upload</title>

<script type="text/javascript">


function upload() {
    // 1. Create XHR instance - Start
    var dat= "bla";
    document.getElementById("div2").innerHTML = "working";
   if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

    var rad = document.getElementById('fajl');
    var filee = rad.files[0];

    var formData = new FormData();
    formData.append('rad',filee)
    formData.append('var',dat)

    xhr.open('POST', 'upload.php'); 


    xhr.send(formData);

    xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status == 200) {

                document.getElementById("div2").innerHTML = xhr.responseText;
                //alert(xhr.readyState);
                //alert(xhr.status);
             }       
    }
}

</script>
</head>
<body>

<form id="uploadForm"  enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>

</form>
</body>
</html>

upload.php的

<?php

if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");

}}
}
$podatak=$_POST['var'];
echo "$podatak"

?>

問題是我沒有在div2元素中看到PHP腳本響應。 Ajax表現得很奇怪,這使我感到困惑。 我已經將JavaScript Alert命令置於xhr.readyState條件下(現在已注釋)。 當我這樣做時,我會看到輸出,但是當我關閉警報對話框時,瀏覽器會自動重新加載頁面,並使URL像我正在使用GET方法(我正在使用POST)一樣,然后服務器輸出消失。 (?rad = ...中的rad是我的輸入元素的名稱)

在此處輸入圖片說明

當我不使用警報命令時,我根本看不到輸出,因為頁面重定向的速度非常快。 我在想什么?

這是因為您使用的是“提交”按鈕,並且正在提交表單。 默認情況下,表單方法是GET請求。 改為僅一個按鈕:

<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />

默認表單動作(提交)正在執行。

要停止此添加,請向您的點擊處理程序return false

onclick="upload(); return false;" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM