简体   繁体   English

如何在 ember v3.2.5 中使用 jQuery AJAX?

[英]How to use jQuery AJAX in ember v3.2.5?

I tried writing code that gives the alert message inside the function but the success or error block seems doesn't work.我尝试编写代码,在 function 中提供警报消息,但成功或错误块似乎不起作用。

How can I call the function properly?如何正确调用 function? I'm using the latest Ember version (3.2.5).我正在使用最新的 Ember 版本(3.2.5)。 Here is my AJAX code in the app/controller这是我在应用程序/控制器中的 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);
        }
      });
    },
  }
});

You would need to invoke the validateUser action in the template for this controller.您需要为此 controller 调用模板中的validateUser操作。 If the controller is app/controllers/login.js then the template would be app/templates/login.hbs .如果 controller 是app/controllers/login.js那么模板就是app/templates/login.hbs Add <button {{on "click" (action "validateUser)}}>Login</button> there are when you click that button the action would fire.添加<button {{on "click" (action "validateUser)}}>Login</button>当您单击该按钮时,该操作将触发。

However, if you're working with the current 3.25 version of ember you may want to rewrite this using the more idiomatic octane and JS approach.但是,如果您使用的是当前3.25版本的 ember,您可能需要使用更惯用的octane和 JS 方法来重写它。 Which would look like:看起来像:

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);
  }
}

And then the button would look like:然后按钮看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM