dongling0519 2019-04-04 10:30
浏览 377

如何发送js FormData

I'm trying to retrieve data from FormData

js side ajax request

function sendForm()
{
  let form=document.getElementById("myForm");

    var formData = new FormData(); 

    for(var i=0; i<form.length; i++)
    {
       formData.append(form[i].name, form[i].value);
    }
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                   console.log(xmlHttp.responseText)
            }
        }
        xmlHttp.open("post", url); 
       xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
       xmlHttp.send(formData); 
 }

from Go side

func login(w http.ResponseWriter, r *http.Request) {
        r.ParseForm()

        username:= r.FormValue("username")     // Data from the form
        password:= r.FormValue("password") 
        fmt.Println(username,password) //getting empty
    }

I have also tried in postman with form-data option but getting same result but in php it is working fine... in Go lang ,i dont't know how to handle multipart/form-data.

  • 写回答

2条回答 默认 最新

  • duanlingzei0170 2019-04-04 10:38
    关注
    xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
    

    Normally, XMLHttpRequest will read the FormData object and generate the Content-Type header from it.

    Here, you are overriding that by setting the Content-Type explicitly, but you are missing the mandatory boundary parameter so the multipart body can't be decoded.

    Remove the quoted line.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器