代码的实现的效果是,前端发起请求传输json格式的数据到指定的url,
<input type="button" onclick="AjaxRequest()" value="跨域Ajax" />
<div id="container"></div>
<script type="text/javascript">
function AjaxRequest() {
$.ajax({
url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403',
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'list',
success: function (data) {
$.each(data.data,function(i){
var item = data.data[i];
var str = "<p>"+ item.week +"</p>";
$('#container').append(str);
$.each(item.list,function(j){
var temp = "<a href='" + item.list[j].link +"'>" + item.list[j].name +" </a><br/>";
$('#container').append(temp);
});
$('#container').append("<hr/>");
})
}
});
}
</script>
后端view视图函数中接收到callbacks带的参数,然后返回给前端(必须转换为json格式)
def get_service(request):
func = request.GET.get("callbacks")
message = {"status":200,"name":"eason","age":34}
return HttpResponse("%s('%s')"%(func,json.dumps(message)))
cors跨域请求则简单的多,主需要在view中加上这么一句话就行了:“Access-Control-Allow-Origin”指向网站的地址
def get_service(request):
message ={"status":200,"name":"eason","age":34}
response = HttpResponse(json.dumps(message))
response["Access-Control-Allow-Origin"]="127.0.0.1:8080"
return response