Ajax JSONP 可不是一个解决跨域访问问题的好办法。
它也有一些缺点
第一最重要的:JSONP不提供错误处理。如果动态插入的代码正常运行,你可以得到返回,但是如果失败了,那么什么都不会发生。你无法获得一个404的错误,也不能取消这个请求
第二重要的:是如果使用了不信任的服务会造成很大的安全隐患。
ajax——JSONP跨域提交问题:
js 代码:
<script>
// rtype 自定义返回类型参数:3 jsonp
function add_attention(uid, fid, opt, flag) {
$.ajax({
url: ' http://服务器域名/ajax_interface_attention_sms.php',
type: 'GET', //这里用GET
async: false,
data:{uid: uid, opt: opt, flag: flag, fid:fid, gid: 0, rtype: 3},
dataType: 'jsonp', //类型
jsonp: ' callback',//jsonp回调参数,必需
success: function(result) {
alert(result.message); //回调输出
}
});
}
</script>
php 服务端代码:ajax_interface_attention_sms.php
<?php
$callback = isset($_GET['callback']) ? trim($_GET[' callback']) : ''; //jsonp回调参数,必需
.....
$tmp= json_encode($date); //json 数据
echo $ callback . '(' . $tmp.')'; //返回格式,必需
?>
js 代码:
<script>
$("#test").bind("click",function() {$.getJSON("http://www.zhangsuoyong.com/demo/cross/ajax01/2.php?jsoncallback=?",function(data){ alert(data);}); });
$("#test2").bind("click",function(){$.ajax({ url :'http://www.zhangsuoyong.com/demo/cross/ajax01/2.php?jsoncallback=?', dataType : "jsonp",type : "GET", success :function(data){ alert(data);} }); });
</script>
php 服务端代码:
<?php
$callback = isset($_GET[' jsoncallback']) ?trim($_GET[' jsoncallback']) : '';
echo $ callback .'(10)';
?>
不足之处欢迎评论指正。。。