前一阵突发奇想想把网站上一些IFRAME调用彻底去掉,于是就想用ajax+json方式实现,后来发现报“No 'Access-Control-Allow-Origin' header is present on the requested resource”错误。由于ajax不能跨域,所以换成JSONP方式实现,很简单:
1.客户端源码
<!doctype html> <html> <head> <Meta charset="utf-8"> <title>test</title> </head> <body> <script language="javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(function() { var url = "http://192.168.1.102/index_szxx_ajax.PHP"; $.ajax({ type: "get",async: false,url: url,dataType: "jsonp",jsonp: "callback",jsonpCallback:"infolist",success: function infolist(data){//数据返回后的处理函数infolist var backdata=""; for(var a in data){ for(var b in data[a]){ backdata=backdata+data[a][b]+"<br>"; } } $("#backdata").html(backdata); } }); }); </script> <div id="backdata">正在查询...</div> </body> </html>
2.服务器端源码 index_szxx_ajax.PHP
<? require("inc/conn.PHP");?> <? $rows=array(); $sqlinfolist="select * from v_info where info_state=1 and user_class=0 order by update_date desc limit 0,9"; $rs_listinfo=$db->query($sqlinfolist); while(($r=$rs_listinfo->fetch_assoc())==true){ $rows[]=$r; } exit("infolist(".json_encode(gbk2utf8($rows)).");");//返回查询的JSON格式结果集并调用回调函数<span style="font-family: Arial,Helvetica,sans-serif;">infolist</span> //服务器端数据库为gb2312编码,转为JSON格式必须为UTF-8编码否则有汉字的单元值会变成NULL; function gbk2utf8($data){ if(is_array($data)){ return array_map('gbk2utf8',$data); } return iconv('gbk','utf-8',$data); } ?>原文链接:https://www.f2er.com/ajax/163719.html