AJAXでのリクエスト方式と同期非同期の違いのまとめ

2744 ワード

要求方式は、GETとPOSTに分けられる.
GET
最も一般的なHTTPリクエストは、一般的にインターネットでページを閲覧するのがGETです.GET方式のパラメータリクエストはそのままURLに付いてから疑問符で開始します.(JSではwindow.location.searchで取得します).パラメータはencodeURIComponentでエンコードできます.使用方法:
var EnParam = encodeURIComponent(param);
URLは約2 Kの長さ、すなわち2048文字数のみをサポートする.GETを使用してAJAXリクエストを行うと、キャッシュされてページが正しく表示されず、一般的にrandomパラメータ値が加算されます.ajax.send(null).
POSTはサーバにデータを送信して使用する.
formフォームの値を先に取り出して文字列に変換し、&記号で接続する(GETパスパラメータと同じ);コミットデータ量2 GB;ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded')を使用して、コミットされた文字列を処理する必要がある.ajax.send(strings)は、formでコミットする必要がある内容、例えばa=1&b=2のような文字列を表すstringsである.
同期と非同期:
ajax.Openメソッドでは,3番目のパラメータは同期または非同期を設定する.prototypeなどのjsクラスライブラリは、一般的に非同期、すなわちtrueにデフォルト設定されます.まず同期の場合、jsはリクエストの戻りを待ってstatusを取得します.onreadystatechangeイベント処理関数は必要ありません.非同期ではonreadystatechangeイベント処理が必要で、値が4で次の内容を正しく処理します.
(注:ajaxはXMLHTTPリクエストオブジェクトを表します.)
 
  
//
function RequestByGet(nProducttemp,nCountrytemp)
{
var xmlhttp
if (window.XMLHttpRequest)
{
//isIE = false;
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
//isIE = true;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Web page location.
var URL="http://www.baidu.com/;
xmlhttp.open("GET",URL, false);
//xmlhttp.SetRequestHeader("Content-Type","text/html; charset=Shift_JIS")
xmlhttp.send(null);
var result = xmlhttp.status;
//OK
if(result==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
}
xmlhttp = null;
}

//
var xmlhttp
function RequestByGet(nProducttemp,nCountrytemp)
{
if (window.XMLHttpRequest)
{
//isIE = false;
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
//isIE = true;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Web page location.
var URL="http://www.baidu.com/";
xmlhttp.open("GET",URL, true);
xmlhttp.onreadystatechange = handleResponse;
//xmlhttp.SetRequestHeader("Content-Type","text/html; charset=UTF-8")
xmlhttp.send(null);
}
function handleResponse()
{
if(xmlhttp.readyState == 4 && xmlhttp.status==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
xmlhttp = null;
}
}