gpt4 book ai didi

javascript - Ajax上传并添加到数据库

转载 作者:行者123 更新时间:2023-12-02 14:11:16 25 4
gpt4 key购买 nike

我有一个将团队添加到数据库的表单,因此我想将团队插入数据库并将 Logo 上传到团队目录。HTML 表单

        <form action="index.php#list_teams" id="subjectForm" method="post" enctype="multipart/form-data">
<p>
<label>Team name</label>
<input class="text-input medium-input" type="text" id="name" name="name" maxlength="20" />
</p>
<br>
<p>
<label>Team Logo (50x50px) </label>
<div id="image_preview"><img id="previewing" src="images/preview.png" /></div>
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" />
<h4 id='loading' >loading..</h4>
<div id="message"></div>
</div>
</p>
<br />
<br />
<br />
<p>
<input class="btn" type="submit" value="Add" />&#32;
<input class="btn" type="reset" value="Reset" />
</p>
</form>

JS

$(document).ready(function(){
$('#subjectForm *').each(function(){
if(this.type=='text' || this.type=='textarea'){
$(this).blur(function(){
validForm(this.form,this.name);
});
}
});
$('input[type="submit"]').click(function(){
if(validForm(this.form,'')){
$.ajax({
url: 'post.php',
type: 'POST',
data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + '&file=' + encodeURIComponent($('#file').val()),
success: function(data) {
$('#notice').removeClass('error').removeClass('success');
var status = data.split('|-|')[0];
var message = data.split('|-|')[1];
$('#notice').html('<div>'+ message +'</div>').addClass(status);
$('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
$('#name').val('');
$('#file').val('');
}
});
}
return false;
});
$('input[type="reset"]').click(function(){
$('.content-box-content').find('span.input-notification').each(function(){
$(this).remove();
});
$('.content-box-content *').each(function(){
$(this).removeClass('error');
})
});

这是 POST.php

if ($_POST['do'] == 'addteam')
{
$name = urldecode($_POST['name']);
$file = urldecode($_POST['file']);
$db->query_write('INSERT INTO teams(name,image) VALUES ("' .
$db->escape_string($name) . '","' . $db->escape_string($file) . '")');
if ($db->affected_rows() > 0)
{
display('success|-|Team has been added into database.');
}
display('error|-|Something went wrong with database!');
}

我想知道现在如何上传 Logo ,我尝试在另一个 php 文件上发布该文件,该文件将上传该文件,但无法在提交时执行两个 ajax 发布。

这是我的上传代码

    if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("../style/images/teams/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "../style/images/teams/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}

那么我如何在ajax上调用两个帖子或删除文件提交上的encodeURIComponent。

最佳答案

您的代码中需要更改一些内容,例如:

  • 使用 event.preventDefault(); 来阻止您的表单被提交,这样您就不需要返回任何 false函数的值。

    $('input[type="submit"]').click(function(event){
    event.preventDefault();
    //your code
    });
  • 如果您通过 AJAX 上传文件,请使用 FormData目的。但请记住,旧浏览器不支持 FormData 对象。 FormData 支持从以下桌面浏览器版本开始:IE 10+、Firefox 4.0+、Chrome 7+、Safari 5+、Opera 12+。您可以通过以下方式在代码中使用 FormData,

    // If required, change $('form')[0] accordingly
    var formdata = new FormData($('form')[0]);
    formdata.append('ajax', 1);
    formdata.append('do', 'addteam');

    因为这样就不用用这个了,

    data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + ...

    你可以简单地这样做,

    data: formdata,
  • 在 AJAX 请求中设置以下选项:processData: falsecontentType: false。请参阅the documentation了解它们的作用。

    contentType : false,
    processData: false,

因此,解决方案是,保持 HTML 表单不变,并按以下方式更改 jQuery

$(document).ready(function(){
$('#subjectForm *').each(function(){
if(this.type=='text' || this.type=='textarea'){
$(this).blur(function(){
validForm(this.form,this.name);
});
}
});
$('input[type="submit"]').click(function(event){
event.preventDefault();
if(validForm(this.form,'')){
// If required, change $('form')[0] accordingly
var formdata = new FormData($('form')[0]);
formdata.append('ajax', 1);
formdata.append('do', 'addteam');

$.ajax({
url: 'post.php',
type: 'POST',
data: formdata,
contentType : false,
processData: false,
success: function(data) {
$('#notice').removeClass('error').removeClass('success');
var status = data.split('|-|')[0];
var message = data.split('|-|')[1];
$('#notice').html('<div>'+ message +'</div>').addClass(status);
$('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
$('#name').val('');
$('#file').val('');
}
});
}
});
$('input[type="reset"]').click(function(){
$('.content-box-content').find('span.input-notification').each(function(){
$(this).remove();
});
$('.content-box-content *').each(function(){
$(this).removeClass('error');
})
});
});

post.php 上,按如下方式处理表单数据:

<?php
if(isset($_POST['ajax']) && isset($_POST['do']) && isset($_POST['name']) && is_uploaded_file($_FILES['file']['tmp_name'])){

// add team to the database
if ($_POST['do'] == 'addteam'){
$name = $_POST['name'];
$db->query_write('INSERT INTO teams(name,image) VALUES ("' . $db->escape_string($name) . '","' . $db->escape_string($file) . '")');
if ($db->affected_rows() > 0){

// now upload logo
// and when you successfully upload the logo, just do this:
// display('success|-|Team and logo have been added into database.');


}else{
display('error|-|Something went wrong with database!');
}
}
}
?>

关于javascript - Ajax上传并添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39540315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com