ajax与jsonp/ajax本地服务器测试
ajax与jsonp
ajax技术的目的是让javascript发送http请求,与后台通信,获取数据和信息。ajax技术的原理是实例化xmlhttp对象,使用此对象与后台通信。ajax通信的过程不会影响后续javascript的执行,从而实现异步。
同步和异步
现实生活中,同步指的是同时做几件事情,异步指的是做完一件事后再做另外一件事,程序中的同步和异步是把现实生活中的概念对调,也就是程序中的异步指的是现实生活中的同步,程序中的同步指的是现实生活中的异步。
局部刷新和无刷新
ajax可以实现局部刷新,也叫做无刷新,无刷新指的是整个页面不刷新,只是局部刷新,ajax可以自己发送http请求,不用通过浏览器的地址栏,所以页面整体不会刷新,ajax获取到后台数据,更新页面显示数据的部分,就做到了页面局部刷新。
同源策略
ajax请求的页面或资源只能是同一个域下面的资源,不能是其他域的资源,这是在设计ajax时基于安全的考虑。特征报错提示:
XMLHttpRequest cannot load https://www.baidu.com/. No
'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
$.ajax使用方法
常用参数:
1、url 请求地址
2、type 请求方式,默认是'GET',常用的还有'POST'
3、dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html'
4、data 设置发送给服务器的数据
5、success 设置请求成功后的回调函数
6、error 设置请求失败后的回调函数
7、async 设置是否异步,默认值是'true',表示异步
以前的写法:
$.ajax({
url: 'js/user.json',
type: 'GET',
dataType: 'json',
data:{'aa':1}
success:function(data){
......
},
error:function(){
alert('服务器超时,请重试!');
}
});
新的写法(推荐):
$.ajax({
url: 'js/user.json',
type: 'GET',
dataType: 'json',
data:{'aa':1}
})
.done(function(data) {
......
})
.fail(function() {
alert('服务器超时,请重试!');
});
---------------------------------ajax本地服务器测试--------------------------

1 /* 2 NodeJS Static Http Server - http://github.com/thedigitalself/node-static-http-server/ 3 By James Wanga - The Digital Self 4 Licensed under a Creative Commons Attribution 3.0 Unported License. 5 6 A simple, nodeJS, http development server that trivializes serving static files. 7 8 This server is HEAVILY based on work done by Ryan Florence(https://github.com/rpflorence) (https://gist.github.com/701407). I merged this code with suggestions on handling varied MIME types found at Stackoverflow (http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs). 9 10 To run the server simply place the server.js file in the root of your web application and issue the command 11 $ node server.js 12 or 13 $ node server.js 1234 14 with "1234" being a custom port number" 15 16 Your web application will be served at http://localhost:8888 by default or http://localhost:1234 with "1234" being the custom port you passed. 17 18 Mime Types: 19 You can add to the mimeTypes has to serve more file types. 20 21 Virtual Directories: 22 Add to the virtualDirectories hash if you have resources that are not children of the root directory 23 24 */ 25 var http = require("http"), 26 url = require("url"), 27 path = require("path"), 28 fs = require("fs") 29 port = process.argv[2] || 8888; 30 31 var mimeTypes = { 32 "htm": "text/html", 33 "html": "text/html", 34 "jpeg": "image/jpeg", 35 "jpg": "image/jpeg", 36 "png": "image/png", 37 "gif": "image/gif", 38 "js": "text/javascript", 39 "css": "text/css"}; 40 41 var virtualDirectories = { 42 //"images": "../images/" 43 }; 44 45 http.createServer(function(request, response) { 46 47 var uri = url.parse(request.url).pathname 48 , filename = path.join(process.cwd(), uri) 49 , root = uri.split("/")[1] 50 , virtualDirectory; 51 52 virtualDirectory = virtualDirectories[root]; 53 if(virtualDirectory){ 54 uri = uri.slice(root.length + 1, uri.length); 55 filename = path.join(virtualDirectory ,uri); 56 } 57 58 fs.exists(filename, function(exists) { 59 if(!exists) { 60 response.writeHead(404, {"Content-Type": "text/plain"}); 61 response.write("404 Not Found\n"); 62 response.end(); 63 console.error('404: ' + filename); 64 return; 65 } 66 67 if (fs.statSync(filename).isDirectory()) filename += '/index.html'; 68 69 fs.readFile(filename, "binary", function(err, file) { 70 if(err) { 71 response.writeHead(500, {"Content-Type": "text/plain"}); 72 response.write(err + "\n"); 73 response.end(); 74 console.error('500: ' + filename); 75 return; 76 } 77 78 var mimeType = mimeTypes[path.extname(filename).split(".")[1]]; 79 response.writeHead(200, {"Content-Type": mimeType}); 80 response.write(file, "binary"); 81 response.end(); 82 console.log('200: ' + filename + ' as ' + mimeType); 83 }); 84 }); 85 }).listen(parseInt(port, 10)); 86 87 console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");

index.html
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>ajax test</title> 9 10 <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> 11 <script type="text/javascript"> 12 $.ajax({ 13 url:'data.json', 14 type:'get', 15 dataType:'json' 16 }) 17 .done(function(data){ 18 console.log(data); 19 //alert(data.name) 20 $('#p1').html('欢迎'+data.name+'来到网站') 21 }) 22 .fail(function(){ 23 console.log('error') 24 }) 25 26 /* 27 $.ajax使用方法 28 常用参数: 29 1、url 请求地址 30 2、type 请求方式,默认是'GET',常用的还有'POST' 31 3、dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html' 32 4、data 设置发送给服务器的数据 33 5、success 设置请求成功后的回调函数 34 6、error 设置请求失败后的回调函数 35 7、async 设置是否异步,默认值是'true',表示异步 36 */ 37 </script> 38 </head> 39 <body> 40 <h1>页面标题</h1> 41 <p id="p1"></p> 42 </body> 43 </html>
node启动server.js服务


------------------------------------------------jsonp --------------------------------------
jsonp
ajax只能请求同一个域下的数据或资源,有时候需要跨域请求数据,就需要用到jsonp技术,jsonp可以跨域请求数据,它的原理主要是利用了script标签可以跨域链接资源的特性。
jsonp的原理如下:
<script type="text/javascript">
function aa(dat){
alert(dat.name);
}
</script>
<script type="text/javascript" src="....../js/data.js"></script>
页面上定义一个函数,引用一个外部js文件,外部js文件的地址可以是不同域的地址,外部js文件的内容如下:
aa({"name":"tom","age":18});
外部js文件调用页面上定义的函数,通过参数把数据传进去。

jsonp.html
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>jsonp</title> 9 10 <!--<script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>--> <!--利用了script标签跨域链接资源--> 11 12 <script type="text/javascript"> 13 function aa(data){ 14 alert(data.name) 15 } 16 </script> 17 18 <script type="text/javascript" src="data.js"></script> <!--外部js文件调用页面上定义的函数,通过参数把数据传进去--> <!--注意:位置要放在这里,不然放在function aa()上面会报错--> 19 20 </head> 21 <body> 22 23 </body> 24 </html>
jquery_jsonp.html
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>jquery-jsonp</title> 9 10 <script type="text/javascript" src="../js/jquery-1.12.4.min.js"></script> 11 <script type="text/javascript"> 12 $.ajax({ 13 url:'data.js', 14 type:'get', 15 dataType:'jsonp', //这里写jsonp 16 jsonpCallback:'aa' //这里必须写jsonpCallback,引用了data.js的aa 17 }) 18 .done(function(data){ 19 alert(data.name) 20 }) 21 .fail(function(){ 22 console.log("error"); 23 }) 24 </script> 25 </head> 26 <body> 27 28 </body> 29 </html>

-----------------------------------------------------------------------------
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>jsonp公开接口</title> 6 <script type="text/javascript" src="../js/jquery-1.12.4.min.js"></script> 7 8 <script type="text/javascript"> 9 10 $(function(){ 11 $('#txt01').keyup(function(){ //keyup松开键盘 12 var val=$(this).val(); //获取输入框的值 13 14 //搜狗搜素栏联动搜索接口https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=c 15 $.ajax({ 16 url:'https://sug.so.360.cn/suggest?', 17 type:'get', 18 dataType:'jsonp', 19 data:{word:val} 20 }) 21 .done(function(data){ 22 consloe.log(data) 23 $('.list').empty(); 24 25 for(i=0;i<data.s.length;i++){ 26 var $li=$('<li>'+data.s[i]+'</li>'); //动态加载li标签 27 $li.appendTo('.list') 28 } 29 }) 30 .fail(function(){ 31 console.log('error'); 32 }) 33 }) 34 }) 35 36 37 </script> 38 </head> 39 <body> 40 <input type="text" name="" id="txt01"> 41 <ul class="list"></ul> 42 </body> 43 </html>
报错了,不知道为什么,需要待解决

posted on 2019-12-28 12:12 cherry_ning 阅读(396) 评论(0) 收藏 举报
浙公网安备 33010602011771号