前端给后台发请求的方式

4 篇文章 0 订阅

1、fetch

2、xmlHttpRequest

3、html默认的form表单提交

三种方法发送的请求在调试network里面显示的type分别是fetch/xhr/document,证明方式不一样

据说type是指MIME类型,但是类型里并没有找到document,只有doc。存疑?

111111

val requestInit = RequestInit(
    method = HttpMethod.POST,
    body = bodyStr,
    headers = try {
      val h = new Headers()
      h.append("Content-Type", "application/json")
      h
    } catch {
      case e: Exception =>
        val errMsg = Shortcut.errorDetailMsg(e)
        throw e
    },
    credentials = RequestCredentials.`same-origin`
  )
  dom.experimental.Fetch.fetch(
    url, requestInit
  ).toFuture.flatMap { r =>
    //        val contentType = r.headers.get("Content-Type").toString.split(";").toList
    r.text().toFuture
  }.map { rst =>
    rst
  }
} catch {
  case e: Exception =>
    val errorDetailMsg = Shortcut.errorDetailMsg(e)
    throw e
}

 

22222

xmlHttp.onreadystatechange = { e: Event =>
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
    decode[LoginRsp](xmlHttp.responseText).map{rsp=>
           //处理LoginRsp
    }
  }
  else if(xmlHttp.readyState == 4){
    JsFunc.alert("error"+xmlHttp.statusText)
  }

}
xmlHttp.open("POST", url, true)
xmlHttp.setRequestHeader("Content-Type", "application/json")
xmlHttp.send(data)

1、2都可以自有添加自定义的header,但是form自动提交没有

3333333333333333

form的提交用input里的name标识传的参数,value是指,默认跳转

可以返回页面来跳转,不方便处理错误

可以通过target=隐藏iframe,再用iframe的onload方法,监听body里的返回string,并解析成json来处理。

IE里面的请求返回applicaiton/json,前端用iframe接收是会出现下载提示,是IE不能解析json,页面将会无操作

可以通过把后台返回的类型改为“text/plain”或"text/html"解决适配

测试ok...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值