企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# ajax ## 1.一个完整的原生js ajax的步骤 #### 1.创建ajax核心对象 #### 2.与服务器建立连接 #### 3.客户端发送请求 #### 4.服务器响应 ***** ### 1.1get请求 ~~~ var url = "xxx"; var xhr = new XMLHttpRequest(); xhr.open('get',url,true); xhr.send(); xhr.onreadystatechange = function(){ // readystate值代表服务器响应的变化, status:以数字形式返回http的状态码 if(xhr.readyState == 4 && xhr.status == 200){ var txt = JSON.parse(xhr.responseText); console.log(txt); } } ~~~ JSON.parse()方法将json对象解析为JavaScript对象。 JSON.stringify()将javascript的值,转换为JSON字符串。 ### 1.2post请求 Post方式要设置一个请求头 ~~~ <div id="test"></div> <script> var test = document.getElementById("test"); var xhr = new XMLHttpRequest(); xhr.open("post","xxx",true); // 设置请求头 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var data = JSON.parse(xhr.responseText); test.innerHTML = data.data.content } } </script> ~~~ ## 2.Jquery ajax()请求 ~~~ window.onload = function(){ $.ajax({ type:"get", //交互方式 url:"xxx", //可以是本地路径 也可以是远程接口地址 dataType:"json", //数据类型 如果是跨域的情况为jsonp success:function(res){ //获取|提交 数据 成功执行的函数 console.log(res); }, error:function(xhr){//失败执行的函数 document.body.innerHTML = xhr.status; } }) } ~~~ ### 2.1$.get() ~~~ //$.get()语法 $.get(url,function(data,status){ //获取的data是一个JS对象 }).fail(function(data){ console.log(data.status) }) ~~~ ### 2.2$.post() ~~~ //$.post()语法 $.post(url,data,function(data,status){ }).fail(function(data){ console.log(data.status) }) ~~~