jQuery JSONP 跨域实践
jQueryJSONP跨域实践
一客户端(url:http://192.168.1.2:81/jsonp_test.jsp)
客户端页面首先在body中放置一个div:<divid="res"></div>将远程调用的数据写入该div中
<script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url:'http://192.168.9.5/jsonp_test1.jsp', dataType:"jsonp", jsonp:"jsonpcallback", success:function(data){ var $ul = $("<ul></ul>"); $.each(data,function(i,v){ $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul) }); $("#res").append($ul); } }); }); </script>
服务端(url:http://192.168.9.5/jsonp_test1.jsp)
代码很简单,就是输出一个字符串
比如正常输出json应该是:[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]
jsonp则输出:jsonpcallback([{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}])其中“jsonpcallback”是客户端传过来的
jsonp = request.getParameter("jsonpcallback") str = "[{""id"":""1"",""name"":""测试1""},{""id"":""2"",""name"":""测试2""}]" str = jsonp + "(" +str+")" response.Write(str)
由于jquery在ajax处理中使用的是utf-8编码传递参数的,所以jsonp处理端用utf-8的编码最好,这样省得编码转换了
相关推荐
fengchao000 2020-06-17
adonislu 2020-05-16
zmosquito 2020-05-10
adonislu 2020-05-10
somebodyoneday 2020-04-22
fengchao000 2020-04-22
fengchao000 2020-04-11
Richardxx 2020-03-07
somebodyoneday 2020-03-06
fengchao000 2020-03-05
somebodyoneday 2020-02-16
xiaouncle 2020-02-13
baijinswpu 2020-01-29
fengchao000 2020-01-10
fengchao000 2019-12-25
newthon 2019-12-23
somebodyoneday 2013-07-11