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.