phonegap如何实现跨域请求调用数据
下面是一个简单的 htmljs jsonp跨域请求的列子,当然我们说过phonegap只是一个框架实现phonegap跨域请求调用数据,只需要在html里面实现即可下面是简单的html列子:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$.ajax({
type: "get",
async: false,
url: "http://www.57lehuo.com/index.php?a=index&m=api&method=itemsListGet×tamp=12121512&cid=773&sign=8d6fda3f30ea3517341e1820cd719784",
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"itemsListGet",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
success: function(json){
alert(json.result.title);
},
error: function(){
alert('fail');
}
});
});
</script>
</head>
<body>
</body>
</html>
php后端代码:提示后端代码的部分代码已经省略$items_list = $items_mod->field('id,cid,title,localimg,price,url,likes')->where($sql_where)
->limit($p->firstRow . ',' . $p->listRows)
->order($order)->select();
$items_list=array(
'result'=>$items_list,
'page'=>$page,
'totalPage'=>$totalPage
);
$items_list=json_encode($items_list);
$callback=$_GET['callback'];
echo $callback."($items_list)";
exit;php 返回的 jsonp的格式如下itemsListGet({"result":[{"id":"6","cid":"773","title":"2013\u5e74\u79cb\u88c5\u65b0\u54c1\u5973\u88c5
\u97e9\u7248\u751c\u7f8e\u96ea\u7eba\u886b\u957f\u8896T\u6064\u5973
\u914d\u540a\u5e26\u80cc\u5fc3
\u9001\u76ae\u5e26","localimg":"data\/items\/2013082218\/20130822181005776.jpg","price":"110.00","url":"http:\/\/s.click.taobao.com\/t?e=zGU34CA7K%2BPkqB05%2Bm7rfGGjlY60oHcc7bkKOQiRddrNEyGLx31dnc6%2Fz%2BaQS2UNDUWpebTcEEjBuk1W5odmLS8%3D&pid=mm_30949159_0_0","likes":"0"},{"id":"5","cid":"773","title":"ZOKE\u6cf3\u8863\u5973\u8fde\u4f53\u88d9\u5f0f\u906e\u809a\u5c0f\u80f8\u805a\u62e2\u663e\u7626\u5927\u7801\u97e9\u56fd2013\u65b0\u6b3e\u6e29\u6cc9\u6e38\u6cf3\u8863","localimg":"data\/items\/2013071817\/20130718174707958.jpg","price":"338.00","url":"","likes":"0"},{"id":"4","cid":"773","title":"\u5c0f\u6843\u6cf3\u8863\u8d1d\u8fea\u65af\u65f6\u5c1a\u6ce2\u70b9\u8fde\u4f53\u88d9\u5f0f\u6cf3\u8863\u5973\u5c0f\u80f8\u805a\u62e2\u94a2\u6258\u663e\u7626\u5973\u58eb\u6cf3\u8863","localimg":"data\/items\/20130718\/20130718174053561.jpg","price":"205.00","url":"","likes":"0"}],"page":1,"totalPage":1})注意此格式和 json的区别
json和 jsonp详细区别可以看此文章:
http://www.phonegap100.com/article-72-1.html
浏览器报错啊,怎么办啊?Origin null is not allowed by Access-Control-Allow-Origin. kupig 发表于 2013-9-17 01:55
浏览器报错啊,怎么办啊?Origin null is not allowed by Access-Control-Allow-Origin.
看看思路就可以了 不要复制过去运行,因为地址什么的不一样 http://www.ionic.ren/2015/12/04/ionic%E5%AE%9E%E7%94%A8%E5%8A%9F%E8%83%BD%E4%B8%83-%E8%B0%83%E8%AF%95%E8%B7%A8%E5%9F%9Faccess-control-allow-origin%E9%97%AE%E9%A2%98/
页:
[1]