一、通过api.ajax异步请求取个人服务器数据
apiready = function(){
api.ajax({
url: 'http://119.29.157.60/api/Shop/getAll', // 自己用PHP写的请求数据库的接口
method: 'get',
headers:{
'Content-Type': 'application/json;charset=utf-8'
}
}, function(ret, err) {
if (ret) {
res = $api.jsonToStr(ret);
console.log(res);
} else {
api.toast({
msg: '加载数据失败',
duration: 2000,
location: 'bottom'
});
}
// 隐藏加载状态对话框
api.hideProgress();
});
};
console.log 展示的数据
二、使用APICloud 的云开发
我在云开发的Database中建了一个Class 'shop',(其他五个以下划线为首命名的Class是默认创建的)
apiready = function() {
initShopList();
}
function initShopList() {
// query对象用于构建一个或多个查询条件,包含分页、排序、以及其它where语句等,设置查询条件后,传递给model对象的查询方法,以获取符合条件的记录。
var query = api.require("query");
// 创建一个 query 对象
query.createQuery(function(ret, err) {
// qid: query 对象的句柄ID,数字型
var queryId = ret.qid;
// 设置查询仅返回需要的字段
query.justFields({
qid: queryId,
value: ['title', 'shopID', 'thumbnail', 'introduce', 'saleNum', 'startPrice', 'getPrice']
});
// 通过model对象,可以对云端指定表内数据进行修改,以及通过查询条件进行查询。注:如果不是在云端编译的应用中测试,则需要调用config方法,配置appKey等信息
var model = api.require("model");
model.findAll({ // 查找表中的所有数据
class: 'shop', // 查找shop Class 表中的数据
qid: queryId
}, function(ret, err) {
if (ret) {
$res = $api.jsonToStr(ret);
console.log($res); // console
api.toast({
msg: '数据获取成功',
duration: 4000,
location: 'bottom'
});
} else {
api.toast({
msg: '数据加载错误',
duration: 4000,
location: 'bottom'
});
}
});
});
}
在控制台中显示了从 shop 表中取出的数据