[英]Syntax error unexpected token '>'
我已經在不同的瀏覽器上測試了我的JS代碼,但它似乎在某些瀏覽器和移動瀏覽器上均不起作用。
JS
function req1() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => {
var title = json.title;
var body = json.body;
document.getElementById("newsTitle").innerHTML = title;
document.getElementById("newsContent").innerHTML = body;
document.getElementById("newsContent2").innerHTML = body;
});
}
req1();
通過閱讀此問題,我了解到該問題可能與“ =>”有關,因為它是ES6元素,並非所有瀏覽器都支持。 但是正如您在這里看到的那樣,這似乎是獲取那些json數據的方法: https : //jsonplaceholder.typicode.com/
有沒有一種方法可以避免在此函數中使用'=>'使其在所有瀏覽器上都能正常工作?
例如,這是我在Safari 9上遇到的錯誤:
我嘗試了一些解決方案,但是現在出現此錯誤:
帖子尚未打印,有什么想法嗎?
只需使用常規函數語法而不是ES6箭頭語法即可:
function req1() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function (res) {return res.json()})
.then(function (json) {
var title = json.title;
var body = json.body;
document.getElementById("newsTitle").innerHTML = title;
document.getElementById("newsContent").innerHTML = body;
document.getElementById("newsContent2").innerHTML = body;
});
}
req1();
大多數不支持ES6箭頭語法的瀏覽器不太可能支持Fetch API。 對於那些我建議使用其他形式的HTTP請求或使用Polyfill,例如GitHub的
使用普通函數代替lambda:
"use strict";
function req1() {
fetch('https://jsonplaceholder.typicode.com/posts/1').then(function(response){
return response.json();
}).then(function(json){
var title = json.title;
var body = json.body;
document.getElementById("newsTitle").innerHTML = title;
document.getElementById("newsContent").innerHTML = body;
document.getElementById("newsContent2").innerHTML = body;
});
}
req1();
寫吧
.then(function(json){
代替
.then(response => response.json())
另外,如果您不確定腳本中的ES6語法,則可以使用類似babel的方法 :
您需要使用訪存polyfill和舊函數語法而不是es6的新箭頭函數語法。
function req1() { fetch('https://jsonplaceholder.typicode.com/posts/1') .then(function (res) {return res.json()}) .then(function (json) { var title = json.title; var body = json.body; document.getElementById("newsTitle").innerHTML = title; document.getElementById("newsContent").innerHTML = body; }); } req1();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.4/fetch.js"></script> <div id="newsTitle"></div> <div id="newsContent"> </div>
瀏覽器對Fetch API polyfill的支持
更改以下行
then(response => response.json())
至
.then(function(response){ response.json() })
和
.then(json => {
至
.then(function (json) {
完整代碼:
function req1() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response){ response.json()})
.then(function (json){
var title = json.title;
var body = json.body;
document.getElementById("newsTitle").innerHTML = title;
document.getElementById("newsContent").innerHTML = body;
document.getElementById("newsContent2").innerHTML = body;
});
}
req1();
為什么不使用簡單的請求
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "https://jsonplaceholder.typicode.com/posts/1", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
var json = JSON.parse(serverResponse);
alert(json.title);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.