javascriptを使用してhtml5でajax要求を作成するには、 xmlhttprequest
オブジェクト(またはより最新 fetch api)を活用します。両方の方法を使用してそれを行う方法は次のとおりです。
xmlhttprequest
:
<code class="javascript"> function makeajaxrequest(url、method、callback){const xhr = new xmlhtprequest(); xhr.open(method、url); xhr.onload = function(){if(xhr.status&gt; = 200&amp;&amp; xhr.status&lt; 300){callback(null、xhr.response); //成功、コールバックへの応答をパス} else {callback(xhr.status、null); //エラー、ステータスコードをコールバックに渡す}}; xhr.onerror = function(){callback(xhr.status、null); //ネットワークエラーを処理}; xhr.send(); } //例:makeajaxrequest( 'data.json'、 'get'、function(error、response){if(console.error){console.error( 'error:'、error);} else {response: '、json.parse(response));}}); <code> MakeajaxRequest </code> URL、HTTPメソッド(GET、投稿など)、およびコールバック関数を引数として使用します。 <code> xmlhttprequest </code>オブジェクトを作成し、<code> onload </code>(成功したリクエスト)および<code> onerror </code>(ネットワークエラー)のイベントリスナーを設定し、リクエストを送信します。コールバック関数は応答またはエラーを処理します。 <p> <strong> <code> fetch </code> api:</strong> </p> <pre class="brush:php;toolbar:false"> <code class="javascript"> function makefetchrequest(url、method、body){const options = {method:method:headers:{'content-type': 'アプリケーション/json'///// json.stringify(body)// jsonデータを使用した投稿要求の場合}; fetch(url、options).then(response =&gt; {if(!respons.ok){throw new error( `http error!status:$ {respons.status}`);} return respons.json(); // parse json response})。 console.error( 'error:'、error); } //例:makefetchRequest( 'data.json'、 'get')makefetchrequest( 'submit_data.php'、 'post'、{name:&quot; john doe&quot;、email:&quot; quot; john@example.com"}); </code>
content-type
ヘッダーを調整することを忘れないでください。 xmlhttprequest
オブジェクトの response> response.ok
プロパティの code>プロパティのプロパティを常に調べてください。 200-299範囲外のステータスコードは、エラー(例えば、404が見つかりません、500内部サーバーエラー)を示します。 <code> xmlhttprequest
で onerror
イベントを聞くか、 .catch()
block in fetch> fetch
。これにより、ユーザーは問題を理解し、適切なアクションを実行できます。集中エラー処理メカニズムを使用してデバッグの目的でエラーを記録することを検討してください。
fetch> code>を使用した詳細なエラー処理:
<code class="javascript"> fetch(url).then(response =&gt; {if(!respons.ok){if(response.status == 404) == 500){'サーバーエラー。後でもう一度試してください。 //ユーザーフレンドリーなエラーメッセージアラート(error.message); </code>
キャッシュコントロール
)を使用して、キャッシュを効果的に管理します。 async/await
を使用するか、非同期操作を効率的に管理することを約束します。以上がHTML5でJavaScriptでAJAXを要求する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。