异步 HTTP 请求
参数名 | 类型 | 是否可选 | 默认值 | 含义 |
---|---|---|---|---|
options |
Object |
请求选项 | ||
options.url |
String |
请求 URL 地址 | ||
options.type |
String |
可选 | text |
响应的类型,可选值: json jsonp text |
options.method |
String |
可选 | GET |
请求方式,可选值: GET POST |
options.contentType |
String |
可选 | application/x-www-form-urlencoded |
请求的 Content-Type ,指明客户端向服务端发送的数据类型。参考:HTTP Content-Type |
options.headers |
Object |
可选 | {} |
请求头 |
options.data |
Object String |
可选 | null |
请求携带的数据,必须是 JSON 对象或 query string |
options.timeout |
Number Boolean |
可选 | false |
超时时间,单位:ms,为 false 时表示不考虑超时 |
options.crossOrigin |
Boolean |
可选 | false |
请求是否跨域 |
options.withCredentials |
Boolean |
可选 | false |
对于跨域请求是否携带 Cookie 信息 |
options.jsonpCallback |
String |
可选 | callback |
JSONP 请求的回调函数字段的 key,即服务端从此字段中取回调函数名,详细解释见下文 |
options.jsonpCallbackName |
String |
可选 | 由程序自动生成 | JSONP 请求的回调函数字段的 value,即回调函数名,详细解释见下文 |
options.success |
Function |
可选 | 调用成功的回调函数 | |
options.error |
Function |
可选 | 调用失败的回调函数 |
当通过 JSONP 形式请求服务端获取数据时,客户端需要告知服务端返回数据时,哪个JS函数将处理这些数据。
例如,请求 http://qianniu.taobao.com/api/todo
,jsonpCallback
的默认值为 callback
,jsonpCallbackName
的值为随机生成 reqwest_1494403163219
,则实际请求的 URL 是 http://qianniu.taobao.com/api/todo?callback=reqwest_1494403163219
。
服务端返回结果如下:
reqwest_1494403163219({ // 数据内容 })
客户端通过预定义名称为 reqwest_1494403163219
的函数等待服务端返回结果,并传入该函数进行下一步的数据处理(回调开发者传入的 success
等)。
但是有时服务端实现的 JSONP 接口所接收的 JSONP 回调函数字段不是 callback
,假设为 qianniu_callback
,此时开发者在调用接口的时候,就可以传入 jsonpCallback
的值为 qianniu_callback
以进行正确请求。
jsonpCallbackName
一般由程序自动生成,确保 success
和 error
回调的正确执行,基本不需要修改。当然你也可以根据你自己的规则生成 jsonpCallbackName
。
参数名 | 类型 | 是否必须返回 | 含义 |
---|---|---|---|
result |
* |
请求响应 |
// JSON 请求 QN.ajax({ url: 'http://qianniu.taobao.com/api/todo', type: 'json', method: 'POST', contentType: 'application/json', headers: { 'Accept': 'application/json', 'X-My-Custom-Header': 'SomethingImportant' }, data: {x: 3, y: 4}, crossOrigin: true, withCredentials: true, }) .then(result => { console.log(result); }) .catch(error => { console.log(error); }); // JSONP 请求 QN.ajax({ url: 'http://qianniu.taobao.com/api/todo', type: 'jsonp', data: {x: 3, y: 4}, jsonpCallback: 'foo', jsonpCallbackName: 'bar', }) .then(result => { console.log(result); }) .catch(error => { console.log(error); }); // 使用回调函数 QN.ajax({ url: 'http://qianniu.taobao.com/api/todo', type: 'jsonp', data: {x: 3, y: 4}, jsonpCallback: 'foo', jsonpCallbackName: 'bar', success(result) { console.log(result); }, error(error) { console.log(error); } });