不能变更的是:接口请求地址,接口url参数名,必须传递的参数必须给它传回去,这样服务器才会响应你的请求,服务器一般会返回json格式的数据给你进行调用。每个接口都有自己的开发手册,主要是介绍:请求格式说明、返回值说明、参数说明等。
言归正传,jquery ajax和js中用ajax提交html代码内容的方法是差不多,举个例子:<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#b01").click(function(){//单击按钮b01的时候触发这个事件
htmlobj=$.ajax({url:"/jquery/test1.txt",async:false}) //定义一个对象,从后台获取test1.txt文件内容
$("#myDiv").html(htmlobj.responseText) //将上面定义的对象中的内容给页面赋值
})
})
</script>
</head>
<body>
<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
<button id="b01" type="button">改变内容</button>
</body>
</html>
语法:jQuery.ajax([settings])
上面的例子没有传参给后台,而是从后台获取,下面的是一个jquery jaxa的向后台传递的例子:
JQUERY:
$.ajax({
type:'post',//可选get
url:'action.php',//这里是接收数据的PHP程序
data:'data='dsa'',//传给PHP的数据,多个参数用&连接
dataType:'text',//服务器返回的数据类型 可选XML ,Json jsonp script html text等
success:function(msg){
//这里是ajax提交成功后,PHP程序返回的数据处理函数。msg是返回的数据,数据类型在dataType参数里定义!
},
error:function(){
ajax提交失败的处理函数!
}
})
1、使用ajax发送数据的步骤
第一步:创建异步对象
var xhr = new XMLHttpRequest()
第二步:设置 请求行 open(请求方式,请求url):
// get请求如果有参数就需要在url后面拼接参数,
// post如果有参数,就在请求体中传递 xhr.open("get","validate.php?username="+name)
xhr.open("post","validate.php")
第三步:设置请求(GET方式忽略此步骤)头:setRequestHeader()
// 1.get不需要设置
// 2.post需要设置请求头:Content-Type:application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
第四步:设置请求体 send()
// 1.get的参数在url拼接了,所以不需要在这个函数中设置
// 2.post的参数在这个函数中设置(如果有参数)
xhr.send(null) xhr.send("username="+name)
第五步:让异步对象接收服务器的响应数据
一个成功的响应有两个条件:
xhr.onreadystatechange = function(){
if(xhr.status == 200 &&xhr.readyState == 4){
console.log(xhr.responseText)
}
ajax-get方式请求案例:
var xhr = new XMLHttpRequest()
xhr.open("get","validate.php?username="+name)
xhr.send(null)
xhr.onreadystatechange = function(){
if(xhr.status == 200 &&xhr.readyState == 4){
console.log(xhr.responseText)
document.querySelector(".showmsg").innerHTML = xhr.responseText
}
}
ajax-post方式请求案例:
var xhr = new XMLHttpRequest()
xhr.open("post","validate.php")
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send("username="+name)
xhr.onreadystatechange = function(){
// 判断服务器是否响应,判断异步对象的响应状态
if(xhr.status == 200 &&xhr.readyState == 4){
document.querySelector(".showmsg").innerHTML = xhr.responseText
}
}
二、Jquery中的Ajax
$.ajax({
type: "get",// get或者post
url: "abc.php",// 请求的url地址
data: {},//请求的参数
dataType: "json",//json写了jq会帮我们转换成数组或者对象 他已经用JSON.parse弄好了
timeout: 3000,//3秒后提示错误
beforeSend: function () {
// 发送之前就会进入这个函数
// return false 这个ajax就停止了不会发 如果没有return false 就会继续
},
success: function (data) { // 成功拿到结果放到这个函数 data就是拿到的结果
},
error: function () {//失败的函数
},
complete: function () {//不管成功还是失败 都会进这个函数
}
})
// 常用
$.ajax({
type: "get",
url: "",
data: {},
dataType: "json",
success: function (data) {
}
})
$.ajax() 都可以发
$.post(url,data,success,datatype):本质上只能发送post请求
$.get(url,data,success,datatype):本质上只能发送get请求
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)