前言
- jquery 3.4.1
- Google Chrome 77.0.3865.90 (正式版本) (64 位) (cohort: Stable)
方法
- 打开 Chrome Console (F12)。
- 让 Chrome 加载 jquery 。
- 执行 jquery 的 ajax 方法。
操作步骤
- 以调用http://t.weather.sojson.com/api/weather接口(https://www.sojson.com/api/weather.html)为例进行说明。
http://t.weather.sojson.com/api/weather 是接口,没有数据。
http://t.weather.sojson.com/api/weather/city/101030100 是接口带参数city,获取天津的天气预报。
- 在 Chrome 中打开http://t.weather.sojson.com/api/weather。这步很重要。
没有这步,将出现跨域请求异常(Access to XMLHttpRequest at ‘http://t.weather.sojson.com/api/weather/city/101030100’ from origin ‘chrome-search://local-ntp’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.)。
- 在 Chrome 中打开 Console 查看是否支持 ajax。
- 如果Chrome已支持 ajax 方法,则跳过本步。如果Chrome未支持 ajax方法,让 Chrome 加载 jquery 来支持 ajax 方法。
Chrome 加载 jquery 的代码:var script=document.createElement("script"); script.type="text/javascript"; script.src="https://code.jquery.com/jquery-3.4.1.min.js"; document.getElementsByTagName('head')[0].appendChild(script);
- 执行 jquery 的 ajax 方法。
$.ajax({ url: "http://t.weather.sojson.com/api/weather/city/101030100", success: function(ajaxData) { console.log(ajaxData); } });
其它
此种方式能不能使用 ajax jsonp 的方式调用?
答:jsonp必须后端开发配合,返回的json串形式须为callback({0})
、showData({0})
等。得到后端开发的配合,能使用;否则,不能使用。