简体   繁体   English

单击按钮时使用AJAX调用PHP函数

[英]Using AJAX to call PHP function on button click

I am creating a file upload script. 我正在创建文件上传脚本。

What I wanted to do is to upload the file without refreshing the page 我想做的是上传文件而不刷新页面

Here's my code: 这是我的代码:

upload.php upload.php的

<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){

$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');

foreach ($files ['name'] as $position => $file_name) {

    $file_tmp = $files['tmp_name'][$position];
    $file_size = $files['size'][$position];
    $file_error = $files['error'][$position];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    if (in_array($file_ext,$allowed)) {
        if ($file_error === 0) {
            if($file_size<=20971520){
                $file_name_new = uniqid('',true).'.'.$file_ext;
                $file_destination = 'test_uploads/'.$file_name_new;

                if (move_uploaded_file($file_tmp, $file_destination)) {
                    $uploaded[$position] = $file_destination;
                }else{
                    $failed[$position] = '[{$file_name}] failed to upload!';
                }
            }else{
                $failed[$position] = '[{$file_name}] file is too large!';
            }
        }else {
        $failed[$position] = '[{$file_name}] file extension is not allowed!';
        }
    }else{
        $failed[$position] = '[{$file_name}] file extension not allowed!';
    }
}

if (!empty($uploaded)) {
    print_r($uploaded);
}

if (!empty($failed)) {
    print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>

</body>
</html>

I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible. 我想在AJAX上执行此操作,我已经搜索了一些示例,但我希望此操作尽可能简单。

By the way, is it possible for this to run without using any plugins or libraries? 顺便说一句,是否可以在不使用任何插件或库的情况下运行它?

I managed to find a solution for this. 我设法找到了解决方案。 I separated the php script from the html and add a javascript file. 我从html分离了php脚本,并添加了一个javascript文件。 I used ajax to call the PHP file to upload the files. 我使用ajax调用PHP文件来上传文件。

Here's my code; 这是我的代码;

index.php 的index.php

<html>
<head>
<style type="text/css">

.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px; 
}

.uploads a, .uploads span{
display: block;
}

.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px; 
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}

.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
    <fieldset>
        <legend>Upload Files</legend>
        <input type="file" id="file" name="file[]" required multiple>
        <input type="button" id="submit" value="Upload">
    </fieldset>
    <div class="bar">
        <span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
    </div>
    <div id="uploads" class="uploads">

    </div>
    <script type="text/javascript" src="upload.js"></script>

    <script type="text/javascript">
        document.getElementById('submit').addEventListener('click', function(e){
                e.preventDefault();
            var f = document.getElementById('file'),
                pb = document.getElementById('pb'),
                pt = document.getElementById('pt');

                    app.uploader({
                    files:f,
                    progressBar:pb,
                    progressText:pt,
                    processor: 'upload.php',

                    finished: function(data){
                        var uploads = document.getElementById('uploads'),
                            succeeded = document.createElement('div'),
                            failed = document.createElement('div'), anchor, span, x;

                            if (data.failed.length) {
                                failed.innerHTML = '<p>The following files failed to upload</p>'

                            }
                            uploads.innerText = '' ;
                            for(x=0; x<data.succeeded.length; x = x+1){
                                anchor = document.createElement('a');
                                anchor.href = 'uploads/' + data.succeeded[x].file;
                                anchor.innerText = data.succeeded[x].name;
                                anchor.target = '_blank';
                                succeeded.appendChild(anchor);
                            }
                            for(x=0;x<data.failed.length; x=x+1){
                                span = document.createElement('span');
                                span.innerText = data.failed[x].name;

                                failed.appendChild(span);   
                            }
                            uploads.appendChild(succeeded);
                            uploads.appendChild(failed);
                    },


                    error: function (){
                        console.log("Error");
                    }
                });
            });
    </script>
</form>
</body>
</html>

upload.php upload.php的

<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {

foreach ($_FILES['file']['name'] as $key => $name) {

    if($_FILES['file']['error'][$key] === 0){
        $temp = $_FILES['file']['tmp_name'][$key];
        $ext = explode('.', $name);
        $ext = strtolower(end($ext));

        $file = md5_file($temp) . time() .'.'.$ext;

        if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
                $succeeded [] = array('name' => $name, 'file' => $file);

            # code...
        }else{
            $failed[] = array('name' => $name );
        }

    }else{

        echo "Error";
    }
  }
}

if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded, 
'failed' =>$failed
));
}
?>

upload.js upload.js

var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;

ajax = function(data){
    var xmlhttp = new XMLHttpRequest(), uploaded;
    xmlhttp.addEventListener('readystatechange', function(){
        if (this.readyState === 4) {
            if (this.status === 200) {
                uploaded = JSON.parse(this.response);
                if (typeof obj.options.finished === 'function') {
                    obj.options.finished(uploaded);
                }
            }else{
                if (typeof obj.options.error === 'function') {
                    obj.options.error();
                }
            }
        }
    });
    xmlhttp.upload.addEventListener('progress',function(){
        var percent;

        if (event.lengthComputable === true) {
            percent = Math.round((event.loaded / event.total) * 100);
            setProgress(percent);
        }
    });

    xmlhttp.open('post', obj.options.processor);
    xmlhttp.send(data);

};

getFormData = function(source){
    var data = new FormData(), i;

    for(i=0; i<source.length; i = i+1){
        data.append('file[]',source[i]);
    }
    data.append('ajax', true);
    return data;
};

setProgress = function (value){
    if (obj.options.progressBar !== undefined) {
        obj.options.progressBar.style.width = value ? value + '%': 0;
    }

    if (obj.options.progressText !== undefined) {
        obj.options.progressText.innerText = value ? value + '%' : 0; 
    }
};

obj.uploader = function(options){
    obj.options = options;

    if (obj.options.files !== undefined) {
        ajax(getFormData(obj.options.files.files));
    }
}
}(app));

anyways, thanks for the help guys. 无论如何,感谢您的帮助。 those were gladly appreciated. 那些人很高兴。 Thanks! 谢谢!

I think in your case the simplest way is to put it into an iframe. 我认为在您的情况下,最简单的方法是将其放入iframe。 I assume you have all code in one PHP file which is called upload.php . 我假设您所有代码都放在一个名为upload.php PHP文件中。 You would get something like this: 您将获得如下内容:

<?php

//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
    if(!empty($_FILES['file1']['name'][0])){

        $files = $_FILES['file1'];
        $uploaded = array();
        $failed = array();
        $allowed = array('jpg','txt','png');

        foreach ($files ['name'] as $position => $file_name) {
            $file_tmp = $files['tmp_name'][$position];
            $file_size = $files['size'][$position];
            $file_error = $files['error'][$position];

            $file_ext = explode('.', $file_name);
            $file_ext = strtolower(end($file_ext));

            if (in_array($file_ext,$allowed)) {
                if ($file_error === 0) {
                    if($file_size<=20971520){
                        $file_name_new = uniqid('',true).'.'.$file_ext;
                        $file_destination = 'test_uploads/'.$file_name_new;

                        if (move_uploaded_file($file_tmp, $file_destination)) {
                            $uploaded[$position] = $file_destination;
                        }else{
                            $failed[$position] = '[{$file_name}] failed to upload!';
                        }
                    }else{
                        $failed[$position] = '[{$file_name}] file is too large!';
                    }
                }else {
                $failed[$position] = '[{$file_name}] file extension is not allowed!';
                }
            }else{
                $failed[$position] = '[{$file_name}] file extension not allowed!';
            }
        }

        if (!empty($uploaded)) {
            print_r($uploaded);
        }

        if (!empty($failed)) {
            print_r($failed);
        }
    }
    exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
    echo '
    <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
    <input type="file" name="file1[]" id="file1" multiple>
    <input type="submit" value="Upload File">
    </form>';   
    exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
    <!-- IFrame which loads the form !-->
    <iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>

Showing uploaded image after successful upload 成功上传后显示上传的图片

you just go through with this code I have already given the answer of this type of question 您只需要完成此代码,我已经给出了此类问题的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM