Home  >  Article  >  Backend Development  >  AJAX uses JSONP to achieve cross-domain data transfer

AJAX uses JSONP to achieve cross-domain data transfer

WBOY
WBOYOriginal
2016-08-08 09:29:20914browse

A while ago, I suddenly thought about completely removing some IFRAME calls on the website, so I wanted to use ajax+json to implement it, but later I found that the message "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. Since ajax cannot cross domains, it is implemented in JSONP mode. It is very simple:

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn