[英]make post request with ajax
我嘗試向api提出一個簡單的請求並返回結果,但是我的請求從未啟動(我也在尋找提琴手)。 我究竟做錯了什么?
<!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>
如果您在控制台中檢查請求,則會看到此錯誤:
語法錯誤:無法對'XMLHttpRequest'執行'setRequestHeader':'Header Name Two'不是有效的HTTP標頭字段名稱。
這是因為標題鍵不能包含空格。 如果將標頭更改為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標頭,您可以從上面的小提琴中看到的新錯誤中看到:
對預檢請求的響應未通過訪問控制檢查:所請求的資源上不存在“ Access-Control-Allow-Origin”標頭
這意味着您需要更改請求以檢索JSONP格式的數據-假設第三方支持該請求,而很多人不支持。 另外,您將需要在服務器而不是JS上發出請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.