Javascript TypeScript-FormData在元素间循环(使用getAll()或entries())
我想离开“jQuery世界”,使用更多的标准JS。不仅是为了增加趣味性,我还决定使用Typescript来增加优点;但问题是: 在发送post请求之前,我需要遍历元素。如果没有Typescript,我可能会使用Javascript TypeScript-FormData在元素间循环(使用getAll()或entries()),javascript,typescript,xmlhttprequest,Javascript,Typescript,Xmlhttprequest,我想离开“jQuery世界”,使用更多的标准JS。不仅是为了增加趣味性,我还决定使用Typescript来增加优点;但问题是: 在发送post请求之前,我需要遍历元素。如果没有Typescript,我可能会使用formDataElement.entries()(或者只检查1个元素formDataElement.getAll('keyFormyFirstery')) 但是PhpStorm和编译器告诉我,没有像“getAll”或“entries”这样的属性 V2A-16:area51 v2a$ ts
formDataElement.entries()
(或者只检查1个元素formDataElement.getAll('keyFormyFirstery')
)
但是PhpStorm和编译器告诉我,没有像“getAll”或“entries”这样的属性
V2A-16:area51 v2a$ tsc --out public/js/d3-fileupload.vanilla.js module/Application/assets/ts/d3-vanilla-fileupload.ts
module/Application/assets/ts/d3-vanilla-fileupload.ts(274,12): error TS2339: Property 'getAll' does not exist on type 'FormData'.
V2A-16:area51 v2a$ tsc --out public/js/d3-fileupload.vanilla.js module/Application/assets/ts/d3-vanilla-fileupload.ts
module/Application/assets/ts/d3-vanilla-fileupload.ts(274,36): error TS2339: Property 'entries' does not exist on type 'FormData'.
下面是我的问题:
- 为什么Typescript在他的库(lib.d.ts)中只支持append,或者有更新的版本
- 我如何在所有元素中循环,以便为我的post请求做好准备
好的-经过几个小时和一些新的白发:
- 并非每个浏览器都支持entry()和getAll();缺少Safari和IE,这就是为什么也缺少typescript支持
- 您需要对元素执行的所有操作,都必须在将其附加到FormData之前执行;在本例中为encodeURIComponent()(是的,这可能很简单)
但是-也许有一个解决方案。我正在考虑对每个对象进行一次小预览,通过这种补救措施,我需要保留每个可用项目的每个模板。在这种情况下,顶部代码中的
后循环选项将是很好的。好的-经过一段时间和一些新的灰色头发后:
- 并非每个浏览器都支持entry()和getAll();缺少Safari和IE,这就是为什么也缺少typescript支持
- 您需要对元素执行的所有操作,都必须在将其附加到FormData之前执行;在本例中为encodeURIComponent()(是的,这可能很简单)
但是-也许有一个解决方案。我正在考虑对每个对象进行一次小预览,通过这种补救措施,我需要保留每个可用项目的每个模板。在这种情况下,顶部代码中的后循环选项将非常好
function FileSelectHandler($event) {
let $files = $event.target.files || $event.dataTransfer.files;
let $targetName = $event.target.getAttribute('data-related-element');
let $relatedElement = document.querySelectorAll('[name="' + $targetName + '"]');
let $uri = $relatedElement[0].getAttribute('data-upload-uri');
let $xhr = new ajax();
if ($files) {
[].forEach.call(
$files,
function ($file) {
$data.append('file[]', $file);
}
);
}
$xhr.post(
$uri,
$data
);
}
class ajax {
[...]
public post(
$url: string,
$data: FormData,
$callback: (text: any) => any = function() {},
$async: any = true
) {
let $query = [];
if ($data !== undefined) {
/*
* Please Help... doesn't work
*/
for (let $key in $data.entries()) {
$query.push(encodeURIComponent($key) + '=' + encodeURIComponent($data[$key]));
}
}
this.send($url, $callback, 'POST', $query.join('&'), $async)
}
}