gpt4 book ai didi

javascript - Ajax 多部分/formdata 发布请求

转载 作者:行者123 更新时间:2023-11-28 05:46:16 24 4
gpt4 key购买 nike

我正在尝试通过 AJAX 向第三方 API 发送发布请求,但返回了这两个我无法超越或修复的错误。

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-provided-api-url

这是我的 HTML 提交表单:

<div class="upload">
<h2>Select a file for upload</h2>
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" id="myFile">
<input type="submit" value="Submit" id ="submit-button">
</form>
</div>

这是我的 AJAX 请求的 jQuery 代码:

$(document).ready(function () {
$("#addProductForm").submit(function (event) {
event.preventDefault();
var formData = $(this).serialize();

$.ajax({
url: 'https://my-provided-api-url',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});

提前谢谢您。

最佳答案

依次处理两个错误:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience

这是因为您使用的是async: false,这是非常糟糕的做法。它会在请求运行时阻止 UI 线程更新,这对用户来说就像浏览器挂起一样。始终使您的请求异步并使用回调来处理响应。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-provided-api-url

这是一个更大的问题。您发出请求的域未启用 CORS。这意味着您无法通过 JavaScript 向他们的 API 发出请求,因为您将被阻止购买 Same Origin Policy 。作为解决方法,您可以向服务器发出本地 AJAX 请求,然后服务器将请求代理给第三方并向您返回数据。

关于javascript - Ajax 多部分/formdata 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38498414/

24 4 0
文章推荐: 用于后期绑定(bind)错误的 C++ dynamic_cast - 切片
文章推荐: ios - 如何在 MKMapSnapshotter 上绘制 CLLocationCoordinate2Ds(在 mapView 打印图像上绘制)
文章推荐: html - 下拉菜单 HTML/CSS
文章推荐: javascript - React 中