我想在 javascript 中使用新的 Fetch 来执行 ajax 请求。这是我为此编写的代码
// Example POST method implementation:
var initial_data = {
'id': 1,
'model-name': 'Joke'
};
postData('/start-jokes', initial_data)
.then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error))
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}
Run Code Online (Sandbox Code Playgroud)
但它会像这样在加载时抛出错误
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Run Code Online (Sandbox Code Playgroud)
在控制台上尝试一下,这也是调用 postData 的响应
Promise { <state>: "pending" }
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Run Code Online (Sandbox Code Playgroud)
不要then(response => response.json()这样使用fetchData。如果调用 API 时出现错误,您无法捕获该错误。
// Example POST method implementation:
var initial_data = {
'id': 1,
'model-name': 'Joke'
};
postData('/start-jokes', initial_data)
.then(response => response.json()) // parses response to JSON
.then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error))
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
}
Run Code Online (Sandbox Code Playgroud)