Home php教程 php手册 js/ajax跨域访问—jsonp的原理和实例(javascript和jquery)

js/ajax跨域访问—jsonp的原理和实例(javascript和jquery)

Jun 06, 2016 pm 08:08 PM
ajax jsonp principle Example access Cross domain

很庆幸,我又见到了末日后新升的太阳,所以我还能在这里写文章,言归正传哈,最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用jsonp来解决,在我们平常的项目中不乏有这种需求的朋友,于是记录下来以便以后查阅同时也希望能帮到大

很庆幸,我又见到了末日后新升的太阳,所以我还能在这里写文章,言归正传哈,最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用jsonp来解决,在我们平常的项目中不乏有这种需求的朋友,于是记录下来以便以后查阅同时也希望能帮到大家。

什么是JSONP协议?
JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。
很明显,JSONP是一种脚本注入(Script Injection)行为,需要特别注意其安全性。

Jquery中的jsonp实例

我们需要两个页面,分别承担协议的客户端和服务器端角色。

客户端代码:



<title>jsonp测试例子</title>
<script type="text/javascript" src="http://www.yzswyl.cn/js/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$.ajax({
type: "get",
async: false,
url: "http://www.yzswyl.cn/demos/jsonp.php",
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"feedBackState",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
success: function(data){
var $ul = $("<ul>");
$.each(data,function(i,v){
$("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
});
$("#remote").append($ul);
},
error: function(){
alert('fail');
}
});
});
</script>


远程数据如下:<br>
<div id="remote"></div>

Copy after login

服务端代码(本例采用PHP):

<?php $jsonp = $_REQUEST["callback"];
$str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';
///////// 注意这里 callback 函数名字直接用了, 攻击者,做些手脚就可以了.
$str = $jsonp . "(" .$str.")";
echo $str;
?>
Copy after login

效果演示:

Jsonp的原理和简单实例

jquery是对其进行了封装,你可能看不到真正的实现方法,我们用下面的一个例子进行说明:

客户端代码:


<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>jsonp测试例子</title>
<script type="text/javascript" src="http://www.yzswyl.cn/js/jquery.min.js"></script>
<script type="text/javascript">
function CallJSONPServer(url){                                 // 调用JSONP服务器,url为请求服务器地址
var oldScript =document.getElementById(url);       // 如果页面中注册了调用的服务器,则重新调用
if(oldScript){
oldScript.setAttribute("src",url);
return;
}
var script =document.createElement("script");       // 如果未注册该服务器,则注册并请求之
script.setAttribute("type", "text/javascript");
script.setAttribute("src",url);
script.setAttribute("id", url);
document.body.appendChild(script);
}
function OnJSONPServerResponse(data){
var $ul = $("<ul>");
$.each(data,function(i,v){
$("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
});
$("#remote").append($ul);
}
</script>


<input type="button" value="点击获取远程数据" onclick="CallJSONPServer('http://www.yzswyl.cn/demos/jsonp_original.php')">
<div id="remote"></div>

Copy after login

服务端代码:

<?php $str = '[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';
$str = "OnJSONPServerResponse(" .$str.")";
echo $str;
?>
Copy after login

效果展示:

别的不多说,相信看代码大家应该明白它是怎么实现的了。

需要注意:

1.由于 jquery 在ajax 处理中使用的是utf-8编码传递参数的,所以jsonp处理端用utf-8的编码最好,这样省得编码转换了,如果不是utf-8记得转换,否则中文会乱码。

2.请求的服务端url最好不要写成http://www.yzswyl.cn/?act=add这样的,应写全其为:http://www.yzswyl.cn/index.php?act=add这样的,在应用的过程中出现了不兼容的情况。

到此就ok了,如有朋友碰到什么问题可发上来大家共同交流。

欢迎大家转载,转载请注明原创 包括链接一定要加上,否则…此处略去n个字

原文参考:http://www.cnblogs.com/xuejie/archive/2012/12/25/2832595.html
更多参考:http://www.nowamagic.net/librarys/veda/detail/224

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

An in-depth discussion of the functions and principles of Linux RPM tools An in-depth discussion of the functions and principles of Linux RPM tools Feb 23, 2024 pm 03:00 PM

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

See all articles