jQuery Ajax使用心得详细整理及注意事项

2019-09-14 07:14:23于丽


当然这个问题一般也不会发生。毕竟咱想请求数据的地方都是咱熟悉的要么就是官方的(什么谷歌地图API,新浪微博API这些显然不会给你坑)。

另一个问题就闹心了。浏览器端对JSONP的请求是否失败是无法直接知晓的。就算用jQuery,error也不起作用。就算出错了try,catch也捕捉不到。

所以暂时知道的只有一种不完美方法,就是设定一个时限,如果超过时限还没有数据返回,那么就判定error。说不完美是因为,各家的网速是不同的,所以...你懂得。
--------------------------------------------------------------------------------
jQuery中contentType相关
jQuery官网原文

contentType
Default: 'application/x-www-form-urlencoded; charset=UTF-8'
When sending data to the server, use this content type.
Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases.
If you explicitly pass in a content-type to $.ajax(),
then it'll always be sent to the server (even if no data is sent).
If no charset is specified, data will be transmitted to the server using the server's default charset;
you must decode this appropriately on the server side.

通过这段文字我们就可以知道在jQuery ajax中 contentType默认是'application/x-www-form-urlencoded; charset=UTF-8' 当然这是最新版jQuery的。相对于以前版本是有些许变化的。

如果想将一个对象序列化后传向后台,可以将contentType设置为'application/json'