摘要: 对于ajax这个API而言,它实际上是有非常多的参数可供开发者选择的,以此满足各种特殊的需求,包括:url、method、cache、timeout、dataType、charset、headers、report、returnAll、data等等,用户可以根据实际情况,结合使用这些参数,来完成非常多的需求,如通常的访问WebService接口获取数据(GET)、提交表单(POST)、上传文件、下载文件等。一个简单的API却包含了非常强大的功能。
下面简单介绍各种类型请求的代码:
1、GET请求代码示例:
api.ajax({ url:'http://m.weather.com.cn/data/101010100.html' //天气预报网站的WebService接口 },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });2、POST请求示例: POST请求-Form表单提交:
api.ajax({ url: 'http://www.xxx.com/path/form', method: 'post', dataType: 'text', //该参数若不传,则默认为json data: { values:{name: 'devlp', password: '123456'} //键值对 } },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });POST请求-单个/多个文件,文件组上传:
api.ajax({ url: 'http://www.xxx.com/path/upLoad', method: 'post', data: { files:{myfile: 'filepath'} // filepath来自ios或者Android的文件系统中的任意文件。可设置多个文件,甚至是文件数组,如files:{myfile: 'filepath', myfile1: 'filepath1'}或者files:{'myfile[]': ['filepath', 'filepath1']}等 } },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });POST请求-提交二进制流:
api.ajax({ url: 'http://www.xxx.com/path/body', method: 'post', data: { body:'textbits' } },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });POST请求-提交文件流:
api.ajax({ url: 'http://www.xxx.com/path/body', method: 'post', data: { stream:'filepath' // filepath来自ios或者Android的文件系统中的任意文件 } },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });POST请求-Multipart-Data,文件和文本字段一起提交:
api.ajax({ url: 'http://www.xxx.com/path/multipart', method: 'post', data: { values:{name: 'devlp', password: '123456'}, files:{file: 'fs://test.png'} } },function(ret,err){ if (ret) { api.alert({msg:JSON.stringify(ret)}); } else { api.alert({msg:JSON.stringify(err)}); }; });POST请求-显示上传进度:
api.ajax({ url: 'http://www.xxx.com/path/multipart', method: 'post', report: true, data: { values:{name: 'devlp', password: '123456'}, files:{file: 'fs://test.png'} } },function(ret,err){ if(ret){ if(0 == ret.status){ //loading('进度:' + ret.progress); }else{ api.alert({msg:'上传成功:\n' + JSON.stringify(ret)}); } }else{ api.alert({msg:JSON.stringify(err)}); } });除此以外,put、delete、head等方式请求使用方式大同小异,在此不做详细叙述。