我尝试向 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');
});
}
上述注意事项
您正在发出跨域请求。 “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/