Ajax

Ajax Cheat sheet - BROWN  JUN 2020


Create XMLHttpRequest Object = > to suit IE 678 & higher


<script>   function check_XMLHttpRequest(){    var xmlHttp;    if(window.ActiveXObject){        // for IE 678 or lower version        xmlRequest=new ActiveXObject("Microsoft.XMLHTTP");    }else if(window.XMLHttpRequest){        xmlRequest=new XMLHttpRequest();    }    alert(xmlRequest)}</script>


Methods=>

xmlHttp.open(“get/post”,”url”);

xmlHttp.send(null); ( if method=post, can add str-data);

PropertyDescription 

onreadystatechangeDefines a function to be called when the readyState property changes 

readyStateHolds the status of the XMLHttpRequest.0: request not initialized1: server connection established2: request received3: processing request4: request finished and response is ready 

responseTextReturns the response data as a string 

responseXMLReturns the response data as XML data 

statusReturns the status-number of a request200: "OK"403: "Forbidden"404: "Not Found" 

statusTextReturns the status-text (e.g. "OK" or "Not Found") 

xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded";




When state change => trigger function => Xml.onreadystatechange=function(event){

If(xmlHttp.readystate===4 && xmlHttp.status===200){

Document.getElementById(“idname”).innerHTML= xmlHttp.responseText;  

==>collect data in url and pass to idname(<div>) for display


==>var json= JSON.parse(xmlHttp.responseText);

 Var str=’’;

For(var i=0;i<json.length;i++){

Str+=json[i].name+”,”+json[i].age+’<br>’;

}}}

Different way to Write

<script>

  $("#b1").on("click", function () {

    $.ajax({

      url:"/ajax_add/", //别忘了加双引号

      type:"GET",  

      data:{"i1":$("#i1").val(),"i2":$("#i2").val()}, //object类型,键值形式的,可以不给键加引号

      success:function (data) {

        $("#i3").val(data);

      }

    })

  })</script>

Example

function xx() {    var request=new XMLHttpRequest();    var url="{% url 'warehouse:update_time_stamp' %}";    var method='post';    var obj=document.getElementById("sid");    var newdate =document.getElementById("newdate");    var olddate=obj.value.toString();    var updatedate=newdate.value.toString();    // alert(olddate+updatedate);    request.open(method,url);    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");    var file= {"A":olddate, "B":updatedate}    request.send(JSON.stringify(file));return false;}    ====> for Django views. Use json.loads(str) => make dict again.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。