使用jquery调试ajax接口

前言

  • jquery 3.4.1
  • Google Chrome 77.0.3865.90 (正式版本) (64 位) (cohort: Stable)

方法

  1. 打开 Chrome Console (F12)。
  2. 让 Chrome 加载 jquery 。
  3. 执行 jquery 的 ajax 方法。

操作步骤

  1. 以调用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,获取天津的天气预报。
    在这里插入图片描述
  2. 在 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.)。
    在这里插入图片描述
  3. 在 Chrome 中打开 Console 查看是否支持 ajax。
    在这里插入图片描述
  4. 如果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); 
    
    在这里插入图片描述
  5. 执行 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})等。得到后端开发的配合,能使用;否则,不能使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值