javascript - Ajax 充当 GET 方法,即使是 POST 方法

标签 javascript php ajax post get

您好,我在使用 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>

上传文件

<?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 警报命令置于 xhr.readyState 条件下(现已注释)。当我这样做时,我会看到输出,但是当我关闭警报对话框时,浏览器会自动重新加载页面并使 URL 就像我正在使用 GET 方法(我正在使用 POST),然后服务器输出消失。 (rad in ?rad=... 是我的输入元素的名称)

enter image description here

当我不使用警报命令时,我根本看不到输出,因为页面重定向非常快。我在误会什么?

最佳答案

这是因为您使用的是提交按钮,它正在提交表单。默认情况下,表单方法是 GET 请求。改为仅使用一个按钮:

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

关于javascript - Ajax 充当 GET 方法,即使是 POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809177/

相关文章:

javascript - ES6。从外部类访问类变量

php - $_REQUEST 有效,但 $_POST 无效 -

php - 如何在 codeigniter 中的不同页面上显示多个 View

javascript - 将 PHP MySQL 调用输入 Charts.js

ajax - ID值从ajax传递但在Action方法中没有接收为什么?

jquery - jasonp跨域请求 "wrapping json into a callback method"

javascript - 提交表单确认文本出现在开头

javascript - 为什么 Firebug 的 console.trace 在跟踪期间将 'anonymous' 报告为函数名称?

javascript - 使用 Codeigniter 403 的 Ajax 请求(禁止)

php - 在 Centos 6.5 上安装 Mycrypt