Ajax向后台发送数据,三种情况:
1:Ajax手动发数据
#GET 发数据
<div> <a class="btn" οnclick="AjaxSubmit1();">点我</a> </div> <script src="/static/js/jquery-3.2.0.js"></script> <script> function AjaxSubmit1() { $.ajax({ url:'/ajax1.html', type:'GET', data:{'p':123}, success:function (arg) { } }) } </script>
#POST 发送数据
function AjaxSubmit3() { $.ajax({ url:'/ajax1.html', type:'POST', data:{'p':123}, success:function (arg) { } }) }
2:HMLHttpRequest方法
#get发送数据
function AjaxSubmit2() { var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function () { if(xhr.readyState==4){ //接受完毕服务器返回的数据 console.log(xhr.responseText); } }; xhr.open('GET','/ajax1.html?p=123'); xhr.send('null'); }
#POST发送数据
function AjaxSubmit4() { var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function () { if(xhr.readyState==4){ //接受完毕服务器返回的数据 console.log(xhr.responseText); } }; xhr.open('POST','/ajax1.html'); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset-UTF-8') xhr.send('p=456'); }
3:Iframe标签+Form表单(‘伪’Ajax)
<h6>基于iframe+Form表单</h6> <iframe id='iframe' name="ifra"></iframe> <form id='fm' action="/ajax1.html" method="POST" target="ifra"> <input name="root" value="111"/> <a οnclick="AjaxSubmit5();">提交</a> function reloadIframe() { {# this.contentWindow#} var content=this.contentWindow.document.body.innerHTML; var obj=JSON.parse(content); if(obj.status){ alert(obj.message); } }
ps:基于Iframe发送数据
<h6>学习iframe</h6> <div> <input id="url" placeholder="请输入URL"/><a οnclick="Test1();">查看</a> </div> <iframe id='iframe' style="height: 800px;width: 600px;" src="http://www.autohome.com.cn"></iframe> function Test1() { var url=$('#url').val(); $('#iframe').attr('src',url); }