Send data between php and dart

2019-07-18 11:44发布

问题:

So i am trying to communicate between dart clientside and a php server side using AJAX. Since direct execution is not possible. I compiled the dart to javascript and then run it on a apache server.

json data is generated at client end, But there is no response from the the server

dart code

import 'dart:html';
import 'dart:json';

void main() {
  query("#clicker").on.click.add(callServer);

}

void callServer(Event event) {
  var data ={ 'name':"sendname"}
  ,jsondata=stringify(data);
  print(jsondata);

  var req = new HttpRequest();
  req.open('post','http://localhost:8080/darttest/server.php',true);
  //req.setRequestHeader('Content-type','application/json');
  req.send(jsondata);
  print(req.responseText);
}

php side i just echo the content received

<?php

$name = $_POST['name'];
echo $name;

?>

This is my first try at dart programming, so do let me know if this approach is even possible

回答1:

To read the response, you have to put your code in a callback on readyStateChange :

var req = new HttpRequest();
req.open('post','http://localhost:8080/darttest/server.php',true);
req.on.readyStateChange.add((e){
  if (req.readyState == HttpRequest.DONE && req.status == 200){
    print(req.responseText);
  }
});
req.send(jsondata);

With your code the http request was not processed when you tried to read the response. You have to wait the completion of the request to read the response.



回答2:

Is localhost:8080 serving both the static Dart (as JS), and the php? If not, you're likely coming across the access-control-allow-origin issue (which is a browser security issue).

This prevents one site posting date to another site.

Work-arounds:

  1. Ensure that the site serving php returns the correct CORS headers: http://enable-cors.org/server.html
  2. Serve the static Dart/JS files from the same URL (localhost:8080)

For more information, read these:

  • https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
  • CORS with Dart, how do I get it to work?
  • Creating a bot/crawler

Update Workaround 3 is described here (for Chrome / Dartium): https://groups.google.com/a/dartlang.org/d/msg/misc/kg13xtD7aXA/uxeXXrw3CG8J

You can add the parameter "--disable-web-security" to chrome.exe to disable cross domain check.

(Of course, this is only useful while you are developing)



回答3:

this is not sending data between dart and php. this is sending data from dart to php!!!



标签: php ajax post dart