简体   繁体   English

用ajax发出发布请求

[英]make post request with ajax

I try to make a simple request to an api and get back the result, but my request is never launched (I am also looking in fiddler). 我尝试向api提出一个简单的请求并返回结果,但是我的请求从未启动(我也在寻找提琴手)。 What am I doing wrong? 我究竟做错了什么?

<!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>

If you check the request in the console you'll see this error: 如果您在控制台中检查请求,则会看到此错误:

SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Header Name Two' is not a valid HTTP header field name. 语法错误:无法对'XMLHttpRequest'执行'setRequestHeader':'Header Name Two'不是有效的HTTP标头字段名称。

This is because header keys cannot contain spaces. 这是因为标题键不能包含空格。 If you change the header to Header_Name_Two the code works fine: 如果将标头更改为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 工作实例

Caveat to the above 注意以上

You are making a cross domain request. 您正在提出跨域请求。 The 'mocky.io' domain does not include CORS headers in their response as you can see in the new error you get from the above fiddle: “ mocky.io”域的响应中不包含CORS标头,您可以从上面的小提琴中看到的新错误中看到:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource 对预检请求的响应未通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

This means that you either need to change the request to retrieve JSONP formatted data - assuming that the third party supports that, which many do not. 这意味着您需要更改请求以检索JSONP格式的数据-假设第三方支持该请求,而很多人不支持。 Alternatively you will need to make the request on the server, not JS. 另外,您将需要在服务器而不是JS上发出请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM