jquery - 使用ajax发出post请求

标签 jquery ajax

我尝试向 api 发出一个简单的请求并返回结果,但我的请求从未启动(我也在 fiddler 中查找)。我做错了什么?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button").click(function(){
        makePostRequest("http://www.mocky.io/v2/587ccd320f000081015dxxxx", "dummy_json", null, "post", "json", "div");
    });
});

function makePostRequest(url, data, headers, httpVerb, dataType, elementId){
    alert('click');
    $.ajax({
    url: url,
    type: httpVerb,
    data: data,
    headers: {
        Header_Name_One: 'Header Value One',
        "Header Name Two": 'Header Value Two'
    },
    dataType: 'json',
    success: function (data) {
      alert("success");
    }
}).done(function(msg){
    alert('done');
  });
}
</script>
</head>
<body>

<button id="button">Send an HTTP POST request to a page and get the result back</button>
<div id="div">

</body>
</html>

最佳答案

如果您在控制台中检查请求,您将看到以下错误:

SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Header Name Two' is not a valid HTTP header field name.

这是因为 header 键不能包含空格。如果将 header 更改为 Header_Name_Two,则代码可以正常工作:

$(document).ready(function() {
    $("#button").click(function() {
        makePostRequest("http://www.mocky.io/v2/587ccd320f000081015dxxxx", "dummy_json", null, "post", "json", "div");
    });
});

function makePostRequest(url, data, headers, httpVerb, dataType, elementId) {
    $.ajax({
        url: url,
        type: httpVerb,
        data: data,
        headers: {
            Header_Name_One: 'Header Value One',
            Header_Name_Two: 'Header Value Two'
        },
        dataType: 'json',
        success: function(data) {
            alert("success");
        }
    }).done(function(msg) {
        alert('done');
    });
}

Working example

上述注意事项

您正在发出跨域请求。 “mocky.io”域的响应中不包含 CORS header ,正如您在从上面的 fiddle 获得的新错误中看到的那样:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

这意味着您需要更改请求以检索 JSONP 格式的数据 - 假设第三方支持这一点,但许多第三方并不支持。或者,您需要在服务器上发出请求,而不是 JS。

关于jquery - 使用ajax发出post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41715482/

相关文章:

php - 将 PHP 变量传递回 jQuery $.ajax 函数

javascript - AJAX 请求 jQuery 中的 this 关键字

javascript - 浏览器如何存储 Etag 以及存储多长时间?

javascript - 点击事件未注册

jquery - 我可以链接到 HTML 页面的内部部分吗?

javascript - 如何通过 AJAX 发送单选按钮值?

javascript - 动态替换 div 容器内的数据

jquery - 无论内部 Accordion 的状态如何,确定外部 Accordion 的状态

javascript - 将垂直制表符转换为 Accordion

javascript - 如何在 prime ui 或 jquery datatable "columns"选项的 headerText 中包含 HTML 代码?