首页 > 解决方案 > 使用 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 没有任何问题。

标签: javascriptjqueryajaxapi

解决方案


我建议尝试使用 fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch而不是 jquery,特别是如果 jquery 没有在其他地方的项目中使用(因为有只是不需要)。使用 fetch api,您可以轻松处理 json 响应以及 CORS 问题等。


推荐阅读