使用axios将表单数据发布到api javascript

时间:2018-03-01 07:06:52

标签: javascript axios

我知道很多次都会问这个问题,但是我想使用axios从表单提交数据到api但是当我点击提交按钮时它没有工作,它会清除然后提交为空字段到api。 我知道有一个event.preventDefault()方法可以解决这个问题,但我不知道将它放在我的代码中的哪个位置。
这是我的代码:

    select  a.name, b.id, b.byuid, b.unread, b.starred 
    FROM all_users_table a
    INNER JOIN private_messages b ON a.id = b.byuid A
    INNER JOIN (
      select byuid, max(timesent) max_sent
      from private_messages 
      WHERE b.touid= 4 
      group by byuid
    ) t on t.byuid = b.byuid and t.max_sent = b.timesent
    ORDER BY  b.timesent DESC, b.unread 
    LIMIT $limit_start, $items_per_page

HTML

 window.onload = function submitData(){
  const name = document.getElementById('name').value
  const email = document.getElementById('email').value
  const contacts = document.getElementById('contacts').value
  const location = document.getElementById('location').value
  const username = document.getElementById('username').value
  const password = document.getElementById('password').value

  axios.get('http://example.com/register', {
     investorNames: name,
     investorEmail: email,
     investorContacts: contacts,
     investorLocation: location,
     username: username,
     password: password
  })
  .then(function (response) {
     console.log(response);
  })
  .catch(function (error) {
     console.log(error);
  });
}

1 个答案:

答案 0 :(得分:4)

从onload中删除submitData并将其声明为普通函数

function submitData(){}

并将输入类型从提交更改为按钮

<input class="button" name="submit" type="button" value="submit" onclick="submitData()" />

它有效