首页 > 解决方案 > 如何在javascript中做ajax回调

问题描述

我的场景是,我在 div 中加载了静态数据,加载后我需要进行 ajax 调用并用新数据覆盖静态数据,如何在 javascript 中执行以下操作

由于我是 lit-element 的新手,我不知道如何使用回调函数有点困惑。加载 div 后,我需要进行 ajax 调用并用新数据覆盖静态数据。我被卡住了,请帮助或任何替代方案

import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
export class Example extends LitElement {
  static get properties() {
    return {
      staticobj: {type: Object}
   }
 }

constructor() {
    super();
   this.static=[{
     id: "value1",
     country: "TH",
     fee: 100   
   },{
    id:"value2",
    country: "SG",
    fee: 200
  }]
}

handleCall(id){
 $.ajax({
   url: "/en",
   method: 'get',
   global: false,
   async: false,
   data: {
     value: id
   },
   success: function (data) {
     callback(data, passData)
   }
 })
this.static=data; //override the static data
}

render(){
   this.static.map((e)=>{  
    return html`
   <div id="list">// call the ajax function once div loaded
     <p>${e.id}</p>
     <h6>${e.country}</h6>
     <h5>${e.fee}</h5>

  </div>
   `
   })
 }
}

标签: javascriptajaxexpresslit-element

解决方案


你应该进入 ES6 和 LitElement 思维模式。忘记 JQuery 并使用fetch(最好使用 ES8 async/await)。在 LitElement 的firstUpdated(). 然后替换您的数组本身(如果您替换数组元素本身,则不会看到更改,因为不会呈现更改):

import { html, css, LitElement } from 'lit-element';

export default class FetchLit extends LitElement {
  static get styles() {
    return css`
      :host {
        display: block;
        padding: 5px;
      }
    `;
  }

  static get properties() {
    return {
      users: { type: Array },
    };
  }

  constructor() {
    super();
    this.users = [
      {
        firstName: 'Jane',
        lastName: 'Doe',
        email: 'jane.doe@somewhere.com',
      },
    ];
  }

  // Don't use connectedCallback() since it can't be async
  async firstUpdated() {
    await fetch(`https://demo.vaadin.com/demo-data/1.0/people?count=10`)
      .then(r => r.json())
      .then(async data => {
        this.users = data.result;
      });
  }

  render() {
    return html`
      <ul>
        ${this.users.map(
          u =>
            html`
              <li>${u.lastName}, ${u.firstName} - ${u.email}</li>
            `,
        )}
      </ul>
    `;
  }
}

window.customElements.define('fetch-lit', FetchLit);

你可以在https://stackblitz.com/edit/fetch-lit看到这个例子


推荐阅读