Home >Backend Development >PHP Tutorial >Use simple records with jsonp (1)

Use simple records with jsonp (1)

WBOY
WBOYOriginal
2016-07-29 09:06:22817browse
The usage environment of jsonp is generally available for front-end and back-end exchange when logging in or exchanging data in different domains
Principle:
The introduced js can be from different domains, and the js file can be generated from the background
(What is said here is a bit simple, please go there more Find information)

Use DEMO:

html:
//原生js
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
    // 得到航班信息查询结果后的回调函数
    var returnjs = function(data){
        alert(data.code);
    };
    // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)
    var url = "http://www.return.com/jsonp/get?code=1&callback=returnjs";//数据接收后台
    // 创建script标签,设置其属性
    var script = document.createElement('script');
    script.setAttribute('src', url);
    // 把script标签加入head,此时调用开始
    document.getElementsByTagName('head')[0].appendChild(script);
    </script>
</head>
<body>
</body>
</html>
//jQ版
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here1</title>
<script type="text/javascript" src="jq.js"></script><!-- 记得引入jq -->
</head>
<body>
<script type="text/javascript">
	jQuery(document).ready(function(){
	   $.ajax({
	        type: "get",
	        async: false,
	        url: "http://www.return.com/jsonp/get?code=1",//数据接收后台
	        dataType: "jsonp",
	        jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
	        jsonpCallback:"returnjs",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
	        crossDomain:true,
	        success: function(json){
	            alert(json.code);
	        },
	        error: function(){
	            alert('fail');
	        }
	    });
	});
</script>
</body>
</html>
后台PHP:
<?php
class jsonp{
	public function get(){
		$code=$_GET['code'];
		if($code==1){
			$code=2;
		}
		echo 'returnjs({"code":"'.$code.'"})';
	}
}

The above introduces the simple record of using jsonp (1), including the content. 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