php - PHP e.preventDefault 导致 isset($_POST['submit']) 为假,$img['name'] 为空
问题描述
我需要将带有图像和(稍后)文本的表单提交到 php 表单,它将图像上传到 imgur,并返回 imgur url,这必须在不更改页面的情况下完成,因此我使用 e.preventDefault()和阿贾克斯。
问题是,当我这样做时, isset($_POST['submit']) 是假的,并且 $img['name'] 是空白的。如果我不使用 preventDefault,页面将更改为 upload.php,这是我不想要的,
如何将表单连同所有文件和帖子一起提交,并在完成后将其返回到原始页面以进行警报?任何帮助表示赞赏。
<?
header("Content-Type: text/plain");
$url = 'eg';
$img=$_FILES['img'];
if(isset($_POST['submit']))
{
if($img['name']==''){
echo "<h2>An Image Please.</h2>";
}else{
$filename = $img['tmp_name'];
$client_id="client_id";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$pvars = array('image' => base64_encode($data));
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$out = curl_exec($curl);
curl_close ($curl);
$pms = json_decode($out,true);
$url=$pms['data']['link'];
echo $url;
if($url!=""){
echo $url;//"<h2>Image Uploaded</h2>";
//echo "<img src='$url'/>";
}else{
echo "<h2>There's a Problem</h2>";
echo $pms['data']['error'];
}
}
}else{echo 'no submit';}
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<html>
<button id='dog'>dog</button>
<form id='foo' action="upload.php" enctype="multipart/form-data" method="POST">
Choose Image : <input name="img" size="35" type="file"/><br/>
<input type="submit" name="submit" value="Upload"/>
</form>
</html>
<script>
$('form').on('submit', function (e) {
e.preventDefault();
var xhr = $.post({
url: 'upload.php',
data: $('form').serialize(),
function (data) {
alert(data.responseText);
}
});
$('#dog').click(function(){alert(xhr.responseText);});
});
</script>
解决方案
推荐阅读
- sql-server - 使用 SELECT 的结果从另一个表中提取相关值
- jupyter-notebook - 将 Jupyter Notebook 转换为 HTML 时,有没有办法保留输出单元格滚动?
- javascript - 如何在 Google 表格中新的脚本加载行之后加载函数?
- android - 从 Firebase 实时数据库中检索好友
- excel - 具有分层定价的需求的 Excel 求解器
- angular - 控制值访问器转移焦点
- php - PDOexception : 没有活动事务
- java - 将键盘信息发送到批处理文件
- r - 使用 Observe 或其他反应函数在 Shiny 中输出单个数据框单元格
- java - 字符串加减法程序