JavaScript 使用带有参数的GET

示例

该函数使用GET运行AJAX调用,允许我们将参数(对象)发送到文件(字符串),并在请求结束后启动回调(函数)。

function ajax(file, params, callback) {

  var url = file + '?';

  // 遍历对象并组合网址
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // 使用url作为参数创建一个AJAX调用
  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) {
  // 在此处添加当数据返回此页面时要执行的代码      
  // 例如console.log(response)将在控制台中显示AJAX响应
});

下面显示了如何检索中的url参数cars.php:

if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
  // 他们设置好了,我们可以使用它们!
  $response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
  $response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
  echo $response;
}

如果您具有回调函数,则控制台中的结果将为:console.log(response)

汽车的颜色是紫色。这是沃尔沃300型!