使用帶引數的 GET

此函式使用 GET 執行 AJAX 呼叫,允許我們將引數 (物件) 傳送到檔案 (字串)並在請求結束時啟動回撥 (函式)。

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      callback(xmlhttp.responseText);
    }
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

以下是我們如何使用它:

ajax('cars.php', {type:"Volvo", model:"300", color:"purple"}, function(response) {
  // add here the code to be executed when data comes back to this page      
  // for example console.log(response) will show the AJAX response in console
});

以下顯示瞭如何在 cars.php 中檢索 url 引數:

if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
  // they are set, we can use them !
  $response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
  $response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
  echo $response;
}

如果你在回撥函式中有 console.log(response),那麼控制檯中的結果將是:

你的車的顏色是紫色的。這是沃爾沃 300 型!