Java:
boolean jsonP = false; String cb = request.getParameter("callback"); if (cb !=null) { jsonP true response.setContentType("text/javascript"}else.setContentType("application/x-json"Writerout.getWriter();jsonPout.write+ "(".printdataBlock.toJsonString());");"}
PHP:
$callback = $_REQUEST['callback']; // Create the output object. $output array'a'=> 'Apple','b'=>'Banana' //start output$callback header('Content-Type: text/javascript' echo $callback '(' json_encode$output');'{'Content-Type: application/x-json'); echo json_encode}
ASP.net:
String jsonString "{success: true}" Request.ParamsGetString responseString ""(!String.IsNullOrEmptycb)){ responseString "("")"{= jsonStringResponseWrite(responseString);jsonp客户端代码:
<html>
<head>
<script type='text/javascript'>
function mycallback(record) {
alert(record);//record是返回的数据
}
function jsonPRequest(){
var url = 'http://www.xxx.com/jsonP/request_data.PHP?callback=mycallback';
var script = document.createElement('script');
script.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<!-- 点此按钮请求数据 -->
<button onclick='void jsonPRequest();'>请求数据</button>
</body>
</html>