1. Client source code
<!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. Server-side source code 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); } ?>
The above introduces how AJAX uses JSONP to achieve cross-domain data transfer, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.