File tree Expand file tree Collapse file tree 2 files changed +57
-5
lines changed
Expand file tree Collapse file tree 2 files changed +57
-5
lines changed Original file line number Diff line number Diff line change 22< html lang ="en ">
33< head >
44 < meta charset ="UTF-8 ">
5- < title > Test jQuery jsonp</ title >
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6+ < title > JSONP Request Example</ title >
7+ < style >
8+ body {
9+ margin : 0 ;
10+ padding : 0 ;
11+ background : linear-gradient (to right, # ff7e5f, # feb47b ); /* 暖色系渐变背景 */
12+ height : 100vh ;
13+ display : flex;
14+ justify-content : center;
15+ align-items : center;
16+ }
17+ # requestButton {
18+ padding : 10px 20px ;
19+ font-size : 16px ;
20+ cursor : pointer;
21+ }
22+ </ style >
623</ head >
724< body >
8- < script src =""> </ script >
9- < script type ="text/javascript ">
10-
25+
26+ < button id ="requestButton "> 发起JSONP请求</ button >
27+
28+ < script src ="https://code.jquery.com/jquery-3.6.0.min.js "> </ script >
29+ < script >
30+ $ ( document ) . ready ( function ( ) {
31+ $ ( '#requestButton' ) . click ( function ( ) {
32+ $ . ajax ( {
33+ url : 'http://localhost:10010/' ,
34+ dataType : 'jsonp' , // 指定预期的服务器响应数据类型
35+ success : function ( data ) {
36+ // 处理返回的数据
37+ console . log ( data ) ;
38+ } ,
39+ error : function ( err ) {
40+ // 处理错误情况
41+ console . error ( err ) ;
42+ }
43+ } ) ;
44+ } ) ;
45+ } ) ;
1146</ script >
47+
1248</ body >
13- </ html >
49+ </ html >
Original file line number Diff line number Diff line change 1+ const http = require ( "http" ) ;
2+ const url = require ( "url" ) ;
3+
4+ // 测试用的,忽略即可
5+
6+ http . createServer ( ( request , response ) => {
7+ response . writeHead ( 200 , { "Content-Type" : "application/javascript" } ) ;
8+ const jsonpCallbackFunctionName = url . parse ( request . url , true ) . query . callback ;
9+ console . log ( `jsonpCallbackFunctionName = ${ jsonpCallbackFunctionName } ` ) ;
10+ const result = {
11+ "foo" : "blablabla" ,
12+ "bar" : Math . random ( )
13+ } ;
14+ // 客户端会自动执行这个函数来处理结果
15+ response . end ( `${ jsonpCallbackFunctionName } (${ JSON . stringify ( result ) } )` ) ;
16+ } ) . listen ( 10010 ) ;
You can’t perform that action at this time.
0 commit comments