javascript - 使用 jquery 或纯 JS 处理 JSONP 请求?
问题描述
我正在使用带有 HTML、CSS 和 JS 的 AllWeatherMap api 构建一个天气应用程序。提供的天气详细信息采用 JSONP 格式。我读到 jquery 在后台处理这样的请求。但我的 webapp 不需要任何 jquery 库。那么,我应该使用 jquery 来处理请求还是使用纯 JS 来解决跨源问题。这是我的电话:
http://api.openweathermap.org/data/2.5/weather?zip=201310,IN&appid=[MY_ID]
回复:
{
"coord": {
"lon": 77.57,
"lat": 28.45
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 306.15,
"pressure": 999,
"humidity": 66,
"temp_min": 306.15,
"temp_max": 306.15
},
"visibility": 4000,
"wind": {
"speed": 1.5,
"deg": 110
},
"clouds": {
"all": 40
},
"dt": 1531841400,
"sys": {
"type": 1,
"id": 7809,
"message": 0.0037,
"country": "IN",
"sunrise": 1531785804,
"sunset": 1531835291
},
"id": 200124150,
"name": "Greater Noida",
"cod": 200
}
为什么我们不为像这样的跨域问题烦恼一些api:
https://learnwebcode.github.io/json-example/animals-1.json
访问上述 url 的 json 没有任何问题。
解决方案
我建议尝试使用 fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch而不是 jquery,特别是如果 jquery 没有在其他地方的项目中使用(因为有只是不需要)。使用 fetch api,您可以轻松处理 json 响应以及 CORS 问题等。
推荐阅读
- javascript - 将带有点符号的字符串转换为对象
- c - 如何在C中的二维数组中找到具有相同值的邻居?
- lit-element - LitElement 使用带有绑定的模板
- computer-vision - 为什么 8thWall 会限制图像跟踪的图像纵横比分辨率
- python - 使用 QWebView 绘图
- python - 如何在 VS Code 中为自定义模块设置导入?
- .net - 当用户将“修复应用程序缩放”设置为关闭时,Windows 10 会做什么?我可以检测到该设置并警告用户将其重新打开吗?
- javascript - 在 Ember 2.16 中创建使用 window.confirm() 的集成测试?
- functional-programming - 函数式编程中的全局状态 (F#)
- jestjs - 用 jest 测试一个简单的函数