简体   繁体   中英

How do I POST data from Dart to PHP asynchronously?

I am trying to do some asynch behavior with Dart and PHP. Here's my code:

var data = new FormData();
data.append("name", "testing");
var httpRequest = new HttpRequest();
httpRequest
  ..open('POST', path)
  ..setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
  ..onLoadEnd.listen((e) => requestComplete(httpRequest))
  ..send(data);

path is set correctly. Since I'm doing asynch, I don't want to actually submit an entire form, which is why I have tried making my own FormData object and appending the information that I need to it. However, when I am in PHP, $_POST['name'] is not set. I thought maybe it was the request header, but I tried changing that, and it didn't help. The only way I have gotten this to work (to set $_POST['name'] ) is to change data to "name=testing" . I have tried viewing the raw post data and it results in:

------WebKitFormBoundaryUfDGArtA6R3ZWVoj Content-Disposition: form-data; name="name" testing------
WebKitFormBoundaryUfDGArtA6R3ZWVoj--

Submitting an actual form (without asynch) gives the correct behavior however. Is there another option aside from a key=value string?

The reason it didn't work is when you override the Content-Type header, you also overrode the boundary parameter to it. When posting multipart/form-data it needs additional info called a boundary, which lets it know on what to split the data. In this case the boundary needs to be: ----WebKitFormBoundaryUfDGArtA6R3ZWVoj

I think this is take care of for you if you don't include the content type. The full content=type would be something like 'multipart/form-data; boundary=----WebKitFormBoundaryUfDGArtA6R3ZWVoj' when its all said and done, and must match the contents of your form data once build.

I think FormData takes care of that for you, or at least lets you pull it out and set it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM