代码之家  ›  专栏  ›  技术社区  ›  kabugh

如何将代码从XHR转换为Vue资源?

  •  0
  • kabugh  · 技术社区  · 7 年前

    我想把代码转换成 XHR Vue-Resource 请求。

    XHR:

    var data = "channel=default";
    
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });
    
    xhr.open("POST", "url");
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    
    xhr.send(data);
    

    这是我的密码 Vue资源 但我有个错误:

    this.$http.post(
            'url',
            {
              headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
              body: 'channel=default'
            }
          ).then(response => {
              console.log(response.body);
          }, error => {
              console.error(error);
          });
    

    我不知道我的 vue 代码。我需要通过 channel?default 体内参数。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Julian Paolo Dayag    7 年前

    你可以通过 data 作为 second 参数到 .post 方法。

    必须是JSON格式。

    this.$http.post(
        'url',
        { channel: 'default'},
        {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }
    ).then(response => {
        console.log(response.body);
    }, error => {
        console.error(error);
    });