【问题标题】:How to use jQuery AJAX in ember v3.2.5?如何在 ember v3.2.5 中使用 jQuery AJAX?
【发布时间】:2021-06-14 20:37:42
【问题描述】:

我尝试编写在函数内部给出警告消息的代码,但成功或错误块似乎不起作用。

如何正确调用函数?我正在使用最新的 Ember 版本(3.2.5)。 这是我在应用程序/控制器中的 AJAX 代码

import Controller from '@ember/controller';
import $ from 'jquery';
export default Controller.extend({
  actions: {
    validateUser: function() {
      let res = this;
      var userName = this.get('username');
      var userPassword = this.get('password');

      $.ajax({
        type: "POST",
        url: "InsertServlet",
        data: {
          userId: userName,
          password: userPassword
        },
        success: function(data) {
          if (data == 1) {
            alert('valid user');
          } else {
            alert("Invalid User");
          }
        },
        error: function(xhr, status, error) {
          alert(xhr.responseText);
        }
      });
    },
  }
});

【问题讨论】:

    标签: jquery ajax servlets ember.js


    【解决方案1】:

    您需要在此控制器的模板中调用validateUser 操作。如果控制器是app/controllers/login.js,那么模板就是app/templates/login.hbs。添加<button {{on "click" (action "validateUser)}}>Login</button>,当您单击该按钮时,该操作将触发。

    但是,如果您正在使用当前的 3.25 版本的 ember,您可能需要使用更惯用的 octane 和 JS 方法来重写它。看起来像:

    import Controller from '@ember/controller';
    import { action } from '@ember/object';
    
    export default class LoginController extends Controller {
      @action
      async validateUser(){
        const response = await fetch(url, {
          method: 'POST',
          body: {userId: this.username, password: this.password },
        });
        console.log(response);
      }
    }
    

    然后按钮看起来像:

    <button {{on "click" this.validateUser}}>Login</button>
    

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多