jsonp的方式請求數(shù)據(jù)需要與后端約定好返回的數(shù)據(jù)格式 形如:callback({"a":123})
callback
是前端的一個(gè)方法 括號(hào)里面的{"a":123}
為前端想要的json數(shù)據(jù)
下面寫一個(gè)前后端的例子
服務(wù)端:
var express = require('express');
var app = express();
app.get('/getData',function(req,res){
var json = {
abc:123
};
res.send("callback("+JSON.stringify(json)+")");
})
app.listen(3002,function(){
console.log('run 3002');
})
前端頁面:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function callback(json){
console.log(json);
};
var el = document.createElement('script');
el.src = 'http://192.168.2.35:3002/getData';
document.body.appendChild(el);
</script>
</body>
</html>
運(yùn)行結(jié)果:
image.png