源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

jQuery使用JSONP实现跨域获取数据的三种方法详解

  • 时间:2022-12-15 10:52 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:jQuery使用JSONP实现跨域获取数据的三种方法详解
本文实例讲述了jQuery使用JSONP实现跨域获取数据的三种方法。分享给大家供大家参考,具体如下: [b]第一种方法是在ajax函数中设置dataType为'jsonp'[/b]
$.ajax({
  dataType: 'jsonp',
  url: 'http://www.a.com/user?id=123',
  success: function(data){
    //处理data数据
  }
});

[b]第二种方法是利用getJSON来实现,只要在地址中加上callback=?参数即可[/b]
$.getJSON('http://www.a.com/user?id=123&callback=?', function(data){
  //处理data数据
});

[b]第三种方法是使用getScript方法[/b]
//此时也可以在函数外定义foo方法
function foo(data){
  //处理data数据
}
$.getScript('http://www.a.com/user?id=123&callback=foo');

[b]实例演练:[/b] index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jsonp</title>
<script src="jquery-1.8.0.min.js"></script>
<script>
  $.ajax({
    type : "post",
    url : "jsonp.php?name=zhaoxiace&age=30",
    dataType : "jsonp",
    jsonp: "callbackParam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
    jsonpCallback:"callbackFunction",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
    success : function(data){
      console.log(data.statusCode + "/" + data.message + "/" + data.name + "/" + data.age);
    },
    error:function(){
      alert('请求失败');
    }
  });
</script>
</head>

jsonp.php
<?
$data["age"] = $_GET['age'];
$data["name"] = $_GET['name'];
$data["statusCode"]="200";
$data["message"]="成功";
$tmp= json_encode($data); //json数据
echo $callback . '(' . $tmp .')'; //返回格式,必需
?>

[b]PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:[/b] [b]在线JSON代码检验、检验、美化、格式化工具: [/b][url=http://tools.jb51.net/code/json]http://tools.jb51.net/code/json[/url] [b]JSON[/b][b]在线格式化工具: [/b][url=http://tools.jb51.net/code/jsonformat]http://tools.jb51.net/code/jsonformat[/url] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]json[/b][b]代码在线格式化/美化/压缩/编辑/转换工具: [/b][url=http://tools.jb51.net/code/jsoncodeformat]http://tools.jb51.net/code/jsoncodeformat[/url] [b]在线json压缩/转义工具:[/b] [url=http://tools.jb51.net/code/json_yasuo_trans]http://tools.jb51.net/code/json_yasuo_trans[/url] 更多关于jQuery相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/294.htm]jQuery操作json数据技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/449.htm]jQuery form操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/200.htm]jQuery常用插件及用法总结[/url]》、《[url=http://www.1sucai.cn/Special/451.htm]jQuery扩展技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/539.htm]jQuery表格(table)操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/75.htm]jquery选择器用法总结[/url]》 希望本文所述对大家jQuery程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部