ajax 使用 JSONP 时,只能 GET 不能 POST

tech2025-07-16  5

前言

ajax不支持用 JSONP(JSON with Padding) 跨域发起 post 请求html在线运行https://www.runoob.com/runcode

ajax 为什么不支持用 jsonp 跨域发起 post 请求?

因为 jsonp 的实现方式,导致 jsonp 无法发起 post 请求,实在是力不从心呐。

JSONP的最基本的原理是:动态添加一个<script>标签,而script标签的src属性是没有跨域的限制的。

简单说一下,想了解更多看一下后面的参考或者自行网上查找:

假定需求为:使用 jsonp 方式访问douban的接口https://wthrcdn.etouch.cn/weather_mini?citykey=101090101&callback=callback。该接口的返回内容为:

说明:

该接口返回的内容有个特征,为:callback(xxx);,将上述内容与https://wthrcdn.etouch.cn/weather_mini?citykey=101090101接口对比一下接口看出不同来了。 网页代码 <!DOCTYPE html> <html> <head> <title>test</title> <meta charset="UTF-8"> </head> <body> </body> <script type="text/javascript"> function callback(res){ success(res.data); } function success(res){ alert(JSON.stringify(res)); } </script> <script src='https://wthrcdn.etouch.cn/weather_mini?citykey=101090101&callback=callback' type="text/javascript" charset="UTF-8"></script> </script> </html> 在线运行:https://www.runoob.com/runcode 将上述代码改为使用 ajax 调用。 <!DOCTYPE html> <html> <head> <title>test</title> <meta charset="UTF-8"> <script src="https://lib.baomitu.com/jquery/3.5.0/jquery.min.js"></script> </head> <body> </body> <script type="text/javascript"> $.ajax({ url: "https://wthrcdn.etouch.cn/weather_mini", data: {citykey:'101090101'}, dataType:'jsonp', jsonpCallback:'callback', success: function(res) { alert(JSON.stringify(res)); } }); </script> </script> </html>

说明:

在线运行效果不变。

怎么才能在跨域请求时,发起 post 请求呢?

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

参考

JSONP 原理介绍

https://blog.csdn.net/z69183787/article/details/19191385

JSONP 技术介绍

https://www.cnblogs.com/fnz0/p/6778503.html https://blog.csdn.net/qq_39043923/article/details/88681807 https://blog.csdn.net/u010200636/article/details/83060249

非 JSONP 的跨域方案

https://www.cnblogs.com/guaishushulz/p/6707707.html

天气预报接口

http://wthrcdn.etouch.cn/weather_mini?citykey=101090101&callback=callback

最新回复(0)