最初に、私はあなたとあなたの参照のためにネイティブJavaScriptの実装Ajaxコードを共有しました。特定のコンテンツは次のとおりです
var getXmlhttprequest = function(){if(window.xmlhttprequest){//主流ブラウザーはxmlhttprequestオブジェクトを提供しますnew xmlhttprequest(); } else if(window.activexobject){// IEブラウザーの下位バージョンはxmlhttprequestオブジェクトを提供していません。 }}; var xhr = getxmlhttprequest(); xhr.onedystatechange = function(){console.log(xhr.readystate); if(xhr.readystate === 3 && xhr.status === 200){//取得の成功後に操作を実行する//データはxhr.responsetext console.log(xhr.responsetext); }}; xhr.open( "get"、 "data.php"、true); xhr.send( "");以下では、JavaScriptを使用してネイティブAjaxを実装するいくつかの方法を共有します。
AJAXを実装する前に、xmlhttprequestオブジェクトを作成する必要があります。このオブジェクトを作成するブラウザがサポートされていない場合は、ActiveXObjectを作成する必要があります。特定の方法は次のとおりです。
var xmlhttp;関数createxmlhttprequest(){if(window.activexobject){xmlhttp = new ActiveXObject( "microsoft.xmlhttp"); } else if(window.xmlhttprequest){xmlhttp = new xmlhttprequest(); }(1)以下は、上記で作成されたXMLHTTPを使用して、最も単純なAJAX GETリクエストを実装します。
function doget(url){//パラメーター値を渡すときは、createxmlhttprequest()をcreated createdmlhttprequest()の場合、encodeuriを使用して処理することが最適であることに注意してください。 xmlhttp.open( "get"、url); xmlhttp.send(null); xmlhttp.onreadystatechange = function(){if((xmlhttp.readystate == 4)&&(xmlhttp.status == 200)){alert( 'success'); } else {alert( 'fail'); }}}(2)上記で作成したXMLHTTPを使用して、最も単純なAJAX POSTリクエストを実装してください。
関数dopost(url、data){//パラメーター値を渡すときは、ecodeuriを使用して処理することが最善であることに注意してください。 xmlhttp.open( "post"、url); xmlhttp.setRequestheader( "content-type"、 "application/x-www-form-urlencoded"); xmlhttp.send(data); xmlhttp.onreadystatechange = function(){if((xmlhttp.readystate == 4)&&(xmlhttp.status == 200)){alert( 'success'); } else {alert( 'fail'); }}}上記はこの記事に関するものです。すべての人の学習に役立つことを願っています。