Xmlhttprequest ja jsonile rakendatud eval näited
Allikas: Lambda
Hulga illustreerivate alertidega näide (vt http://dijkstra.cs.ttu.ee/~tammet/ajax.html ja url, kust datat võetakse: http://dijkstra.cs.ttu.ee/~tammet/cgi-bin/data.py
<html> <head> <script> var request; function myupdatefun() { var response; alert("myupdatefun called with"+request.readyState) if (request.readyState == 4) { alert("Server is done, request.readyState == 4!"); if (request.status == 200) { alert("Server sent data ok,request.status == 200!"); response = request.responseText alert("response is: "+response) document.getElementById('sisu2').innerHTML=response; } else if (request.status == 404) alert("Request URL does not exist"); else alert("Error: status code is " + request.status); } } function ajaxcall() { var url; request = new XMLHttpRequest(); url = "http://dijkstra.cs.ttu.ee/~tammet/cgi-bin/data.py" request.open("GET", url, true); request.onreadystatechange = myupdatefun; request.send(null); } </script> <body> Tere kah! <form> <input type="button" value="Proovi!" onclick="ajaxcall()"> </form> <div id="sisu2"></div> </body>
Ilma alertideta, lisatud json evali calliga näide (vt http://dijkstra.cs.ttu.ee/~tammet/ajax2.html) mis võtab datat urlilt http://dijkstra.cs.ttu.ee/~tammet/cgi-bin/otsi.py
<html> <head> <script> var request; var url; var response; var eresp; function myupdatefun() { //alert(request.readyState) if (request.readyState == 4) { //alert("Server is done!"); if (request.status == 200) { //alert("Server sent data ok!"); response = request.responseText //compres=response; //alert(response) eresp=eval(response) compres="<table>\n" for (i=0; i<eresp.length; i++) { //alert(eresp[i]) compres=compres+"<tr>\n" compres=compres+"<td>"+eresp[i][0]+"</td>" compres=compres+"<td>"+eresp[i][1]+"</td>" compres=compres+"<td>"+eresp[i][2]+"</td>" compres=compres+"</tr>\n" } compres=compres+"</table>" //alert(compres); document.getElementById('sisu2').innerHTML=compres; } else if (request.status == 404) alert("Request URL does not exist"); else alert("Error: status code is " + request.status); } } function ajaxcall() { request = new XMLHttpRequest(); url = "http://dijkstra.cs.ttu.ee/~tammet/cgi-bin/otsi.py" request.open("GET", url, true); request.onreadystatechange = myupdatefun; request.send(null); } </script> <body> Tere kah!<form> <input type="button" value="otsi!" onclick="ajaxcall()"> </form> <div id="sisu2"></div> </body>