Javascript 我想将文件发送到api url并获得响应,而不用使用ajax重定向到它
下面的代码是带有ActionAPI链接的表单 这就是我的ajax请求Javascript 我想将文件发送到api url并获得响应,而不用使用ajax重定向到它,javascript,php,ajax,wordpress,Javascript,Php,Ajax,Wordpress,下面的代码是带有ActionAPI链接的表单 这就是我的ajax请求 $('#form1')。提交(函数(e){ $.ajax({ 类型:“POST”, url:“http://www.example.com/uploader", 数据:formdata, 成功:功能(数据){ 警报(数据); } }) }); NDA文件: 您只需在提交事件中将以下代码添加到函数中即可 e、 预防默认值(); 因为,通常它会提交表单。您需要在表单标签中添加enctype,并使用preventDefaul
$('#form1')。提交(函数(e){
$.ajax({
类型:“POST”,
url:“http://www.example.com/uploader",
数据:formdata,
成功:功能(数据){
警报(数据);
}
})
});代码>
NDA文件:
您只需在提交事件中将以下代码添加到函数中即可
e、 预防默认值();
因为,通常它会提交表单。您需要在表单标签中添加enctype,并使用preventDefault来防止页面刷新
您需要序列化数据并发送数据
在success
区域,您需要处理响应
HTML
CORS策略已阻止从源“”访问“”处的XMLHttpRequest:请求的资源上不存在“Access Control Allow origin”标头当您从API外部的域进行Ajax调用时,浏览器会通过安全策略阻止此请求。为了避免这种情况,您需要在请求-响应头访问控制-允许源站
传递域或'*'
中返回,以允许任何域向api请求数据
<form action="http://www.example.com/uploader" id="form1" method="post" name="myForm" enctype="multipart/form-data">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
$('#form1').submit(function(e){
e.preventDefault();
let data = $( this ).serialize()
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: data,
success: function(response){
// success action here
},
error: function(response) {
// error action here
}
});
});