GET请求:如何发送查询?

时间:2014-08-14 13:47:48

标签: get dart

我想知道在应用程序代码中发出GET请求的正确程序是什么。我的意思是,不是在URL中(这是一个好的做法吗?)。

与往常一样,我想举例说明我在寻找什么。所以这就是:

HTML:

(...)
    <div class="input-area">
        <input type="text" value="SOME VALUE" id="text-field">
        <input type="submit" value="Submit" id="button">
    </div>
(...)

我们假设#button动作是“submitForm”。

DART(它不完整):

void submitForm(Event e) {
    e.preventDefault();
    request = new HttpRequest();
    request.onReadyStateChange.listen(dataIsReady);
    request.open("GET", "http://127.0.0.1:8123");
    (???)
}

我想要发生的是作为参数发送到服务器的文本字段的值。为了澄清,我将使用该参数来搜索MySQL数据库中的一些条目(并返回一些JSON数据)。

那么我怎么能用Dart做到这一点?

1 个答案:

答案 0 :(得分:0)

library x;

import 'dart:html';

void main() {

// you can create an URI and use the toString() method to create a 
// String you can pass to the request

  Map query = {
    'xx': 'yy',
    'zz': 'ss'
  };
  Uri uri =
      new Uri(
          path: "http://localhost:8080/myapp/signinService",
          queryParameters: query);
  print('URI: ${uri.toString()}');


  querySelector("#signinForm")..onSubmit.listen(handle);
}

void handle(Event event) {
  event.preventDefault();

// or you can use the form elements formdata

  FormElement formElement = event.target as FormElement;

  var url = "http://localhost:8080/myapp/signinService";

  HttpRequest.request(
      url,
      method: formElement.method,
      sendData: new FormData(formElement)).then(onDataLoaded);
}


void onDataLoaded(HttpRequest req) {
  String response = req.responseText;
  if (response == 1) {
    window.alert("You are signed in!");
  } else {
    window.alert("Sign in failed. Check credentials.");
  }
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="packages/browser/dart.js"></script>
  </head>
  <body>
    <h1>Alarm</h1>

<!-- I used a form element and set the request method here. It can be set in code too -->

    <form id="signinForm" class="form-signin" method="GET">
      <h2 class="form-signin-heading">Please sign in</h2>
      <input type="text" class="input-block-level" name="email" placeholder="Email address">
      <input type="password" class="input-block-level" name="password" placeholder="Password">
      <button class="btn btn-large btn-primary" id="signinBtn" type="submit">Sign in</button>
    </form>
    <script type="application/dart" src="alarm.dart"></script>
  </body>
</html>