jQuery 发送ajax请求
写在前面的话:
利用jQuery 的 ajax() 方法通过 HTTP 请求加载远程数据 是非常简便的,也是常用的功能。W3school网上的资料(里边有各个参数的介绍)
1.常用写法:
$.ajax({ url:'test.php', type:'POST', // 默认为GET data:{ name:'xy',
age:22 }, timeout:5000, // 超时时间 beforeSend:function(xhr){ console.log(xhr) console.log('发送前') }, success:function(result){ console.log(result) }, error:function(xhr,textStatus){ console.log('错误') console.log(xhr) console.log(textStatus) } })
2.如果资源是跨域的,那么请求数据使用jsonp格式的:
$.ajax({ url:"test2.php", type:"post", dataType:"jsonp", jsonp:"callback", data:{ page: 2 }, success:function (result) { console.log(result) }, error:function (error) { console.log(error) } });
3.关于向服务器传递数据的一些补充:
json字符串与json对象之间的转换:
JSON.parse() // json字符串转化为json对象 JSON.stringify() // json对象转化为json字符串 // 例子1: var s = {}; s.a = 'aaaa'; s.b = 'asdasd'; console.log(JSON.stringify(s)) // 字符串 {"a":"aaaa","b":"asdasd"} console.log(JSON.parse(JSON.stringify(s))) // 对象 Object {a: "aaaa", b: "asdasd"}
一般做法是:把页面的数据存在一个对象里面,然后将这个对象转换成json字符串,传给服务器
//例子2:前端向后端发送数据 在一般场景来说,get方法无需JSON.stringify,post方法需要。?? function testFun(data) { $.ajax({
url: "", type: "POST", dataType: "json", data: {data:JSON.stringify(data)}, success: function (data) { console.log(data); } }); } 在点击提交或者保存时候,运行 testFun 函数;
4.有些是需要在发送时设置请求头的,设置方法:在ajax方法里面加一个参数 headers: {你要设置的内容}
例:
headers:{
Accept:"application/json;"
}
以上。
附:
网上找来的原生写法(截的哪位大神的我不知道了),我本人目前还没使用过原生来写 ……
//原生写法 $('#send').click(function(){ //请求的5个阶段,对应readyState的值 //0: 未初始化,send方法未调用; //1: 正在发送请求,send方法已调用; //2: 请求发送完毕,send方法执行完毕; //3: 正在解析响应内容; //4: 响应内容解析完毕;var data = 'name=yang';
var xhr = new XMLHttpRequest(); //创建一个ajax对象
xhr.onreadystatechange = function(event){ //对ajax对象进行监听
if(xhr.readyState == 4){ //4表示解析完毕
if(xhr.status == 200){ //200为正常返回
console.log(xhr)
}
}
};
xhr.open('POST','url',true); //建立连接,参数一:发送方式,二:请求地址,三:是否异步,true为异步
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //可有可无
xhr.send(data); //发送
});
How to install starDIct on suse OS?
python logging usage
How to reset password for unknow root
How to use wget ?
How to only capute sub-matched character by grep
How to inspect who is caller of func and who is the class of instance
How to use groovy script on jenkins
Vim ide for shell development
linux高性能服务器编程 (二) --IP协议详解