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

标签 javascript jquery ajax

我正在尝试通过 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/

相关文章:

ajax - Node.js Express-根据错误类型不同地处理错误

javascript - 如何在 Node.js/Express 中进行重定向(301)?

jquery - 在 JQuery 中更改 <td> 的 id

javascript - ajax beforeSend 不按流程执行

jquery - 使用 jQuery Quicksand 时 CSS 冒泡

javascript - 如何在 Capybara 验收测试中 stub JavaScript 延迟?

javascript - Home Baked Google Instant(只是花哨的 AJAX)

javascript - 轻量级 zxcvbn 替代方案?

javascript - 我可以创建自定义 Ember 数据方法吗?

javascript - 扩展关于 ul li 背景图像的 Twitter Bootstrap 的正确方法是什么