繁体   English   中英

在使用ajax获取JSON数据时,我收到了意外的令牌:错误

[英]While fetching JSON data using ajax i am getting Unexpected token : error

我需要从url获取数据返回的数据是JSON。但是在尝试获取时我正在获取

未捕获的SyntaxError:意外的令牌:

这是代码请检查。

你能告诉我为什么我会收到这个错误以及如何解决它。

 $(document).ready(function () { var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE"; $.ajax({ contentType: 'application/json', dataType: 'json', url: Url + '&callback=?', success: function (data) { alert(data); }, error: function (jqXHR, text, errorThrown) { } });}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

找小提琴链接https://jsfiddle.net/vbpradeep/kf9ad1t3/

看来你无法在JSON中构建URL字符串

而不是像这样在JSON中创建它:

url: Url + '&callback=?',

您可以将其添加到原始URL字符串的末尾:

var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE&callback=?'";

http://codepen.io/nilestanner/pen/pEOgZj

尽管codepen仍显示交叉原点错误,但这会删除语法错误。

我希望这能解决这个问题。

 $(document).ready(function() { var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE&callback=?"; $.ajax({ contentType: 'application/json', dataType: 'json', url: Url }).then(function(data){ //What should happen in success scenarios console.log('Success'); alert(data) },function(data){ //what should happen in failure scenarios console.log('Failure Block'); alert(data) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

从 API 获取数据并记录它时出现此错误“SyntaxError: Unexpected token '<',”<div id="text_translate"><p> 从 API 获取数据并记录它时出现此错误“SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON at App:js:24:1"</p><p> <strong>应用程序.js</strong></p><pre> import { useState } from "react"; import "./App.css"; import CurrentWeather from "./component/current-weather/current-weather"; import { WEATHER_API_KEY, WEATHER_API_URL } from "./component/search/api"; import Search from "./component/search/search"; function App() { const [currentWeather, setCurrentWeather] = useState(null); const [forecast, setForecast] = useState(null); const handleOnSearchChange = (searchData) => { const [lat, lon] = searchData.value.split(" "); const currentWeatherFetch = fetch( `${WEATHER_API_URL}/weather?lat=${lat}&lon=${lon}&appid=${WEATHER_API_KEY}` ); const forecastFetch = fetch( `${WEATHER_API_URL}/forecast?lat=${lat}&lon={${lon}&appid=${WEATHER_API_KEY}` ); Promise.all([currentWeatherFetch, forecastFetch]).then(async (response) => { const weatherResponse = await response[0].json(); const forcastResponse = await response[1].json(); setCurrentWeather({ city: searchData.label, ...weatherResponse, }); setForecast({ city: searchData.label, ...forcastResponse }); }).catch(console.log); }; console.log(currentWeather); console.log(forecast); return ( <div className="container"> <Search onSearchChange={handleOnSearchChange} /> <CurrentWeather /> </div> ); } export default App;</pre><p> <strong>api.js</strong></p><pre> export const geoApiOptions = { method: "GET", headers: { "X-RapidAPI-Key": process.env.REACT_APP_GEODB_API_KEY, "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com", }, }; export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo"; export const WEATHER_API_URL = "api.openweathermap.org/data/2.5"; export const WEATHER_API_KEY = process.env.REACT_APP_WEATHER_API_KEY;</pre><p> 我在浏览器中手动给出了 api 链接并得到了这个结果https://api.openweathermap.org/data/2.5/weather?lat=-27.47&lon=153.12&appid=<API_KEY></p><pre> {"coord":{"lon":153.12,"lat":-27.47},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":296.36,"feels_like":296.75,"temp_min":295.22,"temp_max":297.15,"pressure":1016,"humidity":77},"visibility":10000,"wind":{"speed":3.6,"deg":120},"clouds":{"all":75},"dt":1673616299,"sys":{"type":1,"id":9485,"country":"AU","sunrise":1673550242,"sunset":1673599638},"timezone":36000,"id":2176264,"name":"Belmont","cod":200}</pre><p> 在获得响应而不是响应时出现错误。 不确定我在这里做错了什么。</p><p> 在获得响应而不是响应时出现错误。</p><p> 从评论中得到了如何获得整个回复的建议,这是我得到的,</p><pre> <.DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/favicon,ico" /> <meta name="viewport" content="width=device-width. initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="/logo192.png" /> <.-- manifest:json provides metadata used when your web app is installed on a user's mobile device or desktop. See https.//developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="/manifest.json" /> <.-- Notice the use of in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML, Unlike "/favicon.ico" or "favicon.ico". "/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> <script defer src="/static/js/bundle,js"></script></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <,-- This HTML file is a template, If you open it directly in the browser. you will see an empty page. You can add webfonts, meta tags. or analytics to this file, The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html></pre><p> 没有任何相关的错误</p></div>

[英]While fetching data from API and logging it getting this error "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON at App.js:24:1"

暂无
暂无

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

相关问题 我正在使用Ionic并收到错误消息:SyntaxError:JSON中的意外标记&lt;在JSON.parse位置0处( <anonymous> ) 为什么我在 JSON 中的位置 0 处收到 Unexpected token &lt; 的错误 从 API 获取数据并记录它时出现此错误“SyntaxError: Unexpected token '<',”<div id="text_translate"><p> 从 API 获取数据并记录它时出现此错误“SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON at App:js:24:1"</p><p> <strong>应用程序.js</strong></p><pre> import { useState } from "react"; import "./App.css"; import CurrentWeather from "./component/current-weather/current-weather"; import { WEATHER_API_KEY, WEATHER_API_URL } from "./component/search/api"; import Search from "./component/search/search"; function App() { const [currentWeather, setCurrentWeather] = useState(null); const [forecast, setForecast] = useState(null); const handleOnSearchChange = (searchData) => { const [lat, lon] = searchData.value.split(" "); const currentWeatherFetch = fetch( `${WEATHER_API_URL}/weather?lat=${lat}&lon=${lon}&appid=${WEATHER_API_KEY}` ); const forecastFetch = fetch( `${WEATHER_API_URL}/forecast?lat=${lat}&lon={${lon}&appid=${WEATHER_API_KEY}` ); Promise.all([currentWeatherFetch, forecastFetch]).then(async (response) => { const weatherResponse = await response[0].json(); const forcastResponse = await response[1].json(); setCurrentWeather({ city: searchData.label, ...weatherResponse, }); setForecast({ city: searchData.label, ...forcastResponse }); }).catch(console.log); }; console.log(currentWeather); console.log(forecast); return ( <div className="container"> <Search onSearchChange={handleOnSearchChange} /> <CurrentWeather /> </div> ); } export default App;</pre><p> <strong>api.js</strong></p><pre> export const geoApiOptions = { method: "GET", headers: { "X-RapidAPI-Key": process.env.REACT_APP_GEODB_API_KEY, "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com", }, }; export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo"; export const WEATHER_API_URL = "api.openweathermap.org/data/2.5"; export const WEATHER_API_KEY = process.env.REACT_APP_WEATHER_API_KEY;</pre><p> 我在浏览器中手动给出了 api 链接并得到了这个结果https://api.openweathermap.org/data/2.5/weather?lat=-27.47&lon=153.12&appid=<API_KEY></p><pre> {"coord":{"lon":153.12,"lat":-27.47},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":296.36,"feels_like":296.75,"temp_min":295.22,"temp_max":297.15,"pressure":1016,"humidity":77},"visibility":10000,"wind":{"speed":3.6,"deg":120},"clouds":{"all":75},"dt":1673616299,"sys":{"type":1,"id":9485,"country":"AU","sunrise":1673550242,"sunset":1673599638},"timezone":36000,"id":2176264,"name":"Belmont","cod":200}</pre><p> 在获得响应而不是响应时出现错误。 不确定我在这里做错了什么。</p><p> 在获得响应而不是响应时出现错误。</p><p> 从评论中得到了如何获得整个回复的建议,这是我得到的,</p><pre> <.DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/favicon,ico" /> <meta name="viewport" content="width=device-width. initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="/logo192.png" /> <.-- manifest:json provides metadata used when your web app is installed on a user's mobile device or desktop. See https.//developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="/manifest.json" /> <.-- Notice the use of in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML, Unlike "/favicon.ico" or "favicon.ico". "/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> <script defer src="/static/js/bundle,js"></script></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <,-- This HTML file is a template, If you open it directly in the browser. you will see an empty page. You can add webfonts, meta tags. or analytics to this file, The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html></pre><p> 没有任何相关的错误</p></div> 使用Angular.js时在JSON错误中获取意外令牌 我正在尝试发出 AJAX 获取请求,但我不断收到错误“Uncaught SyntaxError: Unexpected token ')'” 使用jQuery Unexpected token获取Json数据: 使用JSON.parse时,出现“ SyntaxError:JSON中位置1的意外令牌” 解析JSon数据时出现错误“未捕获的SyntaxError:JSON中的位置意外标记x” 我正在尝试执行一个简单的 EJS 程序,但在编译 EJS 时出现意外令牌 &#39;)&#39; 错误 尝试在简单对象上执行JSON.parse时出现“意外令牌”错误
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM