我將這個 ajax 帖子發送到服務器以將一些資料發送到 SQL 資料庫:
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
在服務器中,我使用 php 獲取此資料,如下所示:
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
我也有這個輸入:
<input id="myFileInput" type="file" accept="image/*">
并在與actions.php我有檔案夾的同一目錄中/images
我如何#myFileInput在這個 ajax 帖子中包含一個影像(來自)并使用 php 中的相同查詢將其保存到服務器?
我已經在 SO 中搜索了解決方案,但其中大多數已經超過 10 年了,我想知道是否有一種簡單而現代的方法可以做到這一點,如果是最佳實踐,我愿意學習和使用 fetch api。
uj5u.com熱心網友回復:
您應該使用 formData API 發送您的檔案(https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
我認為你正在尋找的是這樣的:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax 包裝器有一個引數來避免內容處理,這對于檔案上傳很重要。
在服務器端,檔案的 vrey 簡單處理程式可能如下所示:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
uj5u.com熱心網友回復:
通過 ajax FormData 你可以發送它。請參閱此處。注意: data: new FormData(this) - 這會發送整個表單資料(包括檔案和輸入框資料)
網址:https : //www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
uj5u.com熱心網友回復:
如果您不反對使用fetchapi,那么您可以像這樣發送文本資料和檔案:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
在 PHP 方面,您應該使用準備好的陳述句來減輕 SQL 注入,并且應該能夠像這樣訪問上傳的檔案:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329955.html
標籤:javascript php 查询 阿贾克斯 获取 API
上一篇:AJAXPost呼叫無資料
