Binding.scala使用教程10--使用Ajax

这篇教程介绍了在使用Binding.scala时如何进行Ajax操作。由于跨域问题,文章建议使用特定的Scala服务器环境或手动部署到Tomcat或Flask服务器。作者提到了利用Python的watchdog监控文件变化并自动部署,甚至结合selenium自动刷新页面。此外,文中还涉及到使用Binding.scala进行post和get请求的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提醒

  • 如果使用我之前写的开发环境,是无法正确请求到数据的(有跨域问题),需要搭建scalajs的sever,可以使用下面这个代码
  • https://github.com/vmunier/play-scalajs.g8
  • 还有一个最简单的方法就是 手动将编译后的文件复制到 tomcat 或者用flask搭建的小型服务器上。
  • 但是手动拷贝,太愚蠢了(我们可是程序猿,we do something incredible !!!),可以用python的watchdog写个监控软件,当文件被改动后自动拷贝,并且用selenium自动打开谷歌浏览器,刷新页面。用pyinstaller打包成exe。

post 请求

  • binding.scala
@dom def render =
  {
  <div>
    <hr/>
    {
    val formData = new FormData()
    formData.append("username", "my name is jerry")
    formData.append("password", "are you okay")
    val result = FutureBinding(Ajax.post("/hello", data = formData))
    result.bind match
      {
        case None =>
          <div>you got nothing</div>
        case Some(Failure(exception)) =>
          <div>{ "i am the exception " + exception.getMessage + exception.getStackTrace }</div>
        case Some(Success(response)) =>
          val user=JSON.parse(response.responseText)
          <div>
               <p>username={user.username.toString}</p>
               <p>password={user.password.toString}</p>
            <p>password={user.name.toString}</p>
               <p>response.responseText= new text={JSON.stringify(response.responseText)}</p>
              </div>
      }
    }
  <hr/>
  </div>
}
  • flask
@app.route('/hello',methods=['POST'])
def hello():
    print(request.form)
    username=request.form.get('username')
    password=request.form.get('password')
    user={
        "username":username,
        "password":password
    }
    return json.dumps(user)
get 请求
  • binding.scala
@dom def render =
  {
    val result = FutureBinding(Ajax.get("/info"))
  <div>
    {
     result.bind match
     {
       case None =>
         <div>you got nothing</div>
       case Some(Failure(exception)) =>
         <div>{ "i am the exception " + exception.getMessage + exception.getStackTrace }</div>
       case Some(Success(response)) =>
         val info=JSON.parse(response.responseText)
          <div>

             info.code={info.code.toString}
            <p>response.responseText= new text={JSON.stringify(info)}</p>
          </div>
      }
     }
  </div>
  }
  • flask
@app.route('/info')
def info():
    userInfo = {
        'code': 200,
        'msg': 'success',
        'data': {
            'role': 'admin',
            'message':'always easy'
        }
    }
    return json.dumps(userInfo)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值