javascript:点击按钮进行POST调用 [英] javascript: make a POST call on button click

查看:982
本文介绍了javascript:点击按钮进行POST调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过向其添加事件侦听器来在按钮上单击POST,但是使用ajax可以进行调用,但是我没有任何数据或成功信息,错误标准也相同.

I want to make a POST on button click by adding an event listener to it, but with ajax I can make the call but I do not have any data or success, error criteria for the same.

我发现一种使用表单提交事件的方法,但是我猜这不是正确的方法,我应该在单击按钮时进行POST调用.

one way I found was using form submit event, but I guess it is not the right way to do it, I should be making a POST call on button click.

<div id="googleSignInDiv" class="cols-row ">
   <form id="googleSignInform" action="/connect/google" method="post"
      target="google-auth-window">
      <button type="submit" class="btn-primary btn-sub-action  gss-col-12 type-300 social-button google" 
         id="signin-login-google-button" >
      <span class="icon social-icon"></span>
      <span class="btn-label">
      {{[loc-signin-google]}}
      </span>
      </button>
   </form>
</div>

如果我在onclick函数中执行了类似的操作,则它无法正常工作,也不会出现任何错误.

If I do something like this in my onclick function, its not working as desired, neither am getting any error.

$.ajax({
    url: '/connect/google',
    type: 'POST'
});

然后,我就有了打开新窗口的代码.如何进行后期调用并将其目标标记为我在代码中定义的google-auth-window?还是使用表格是正确的方法?

And after this, I have my code to open the new window. How can I make a post call and mark its target as the google-auth-window which I have defined in my code? or using the form is the correct way?

推荐答案

表单中类型为submit的按钮的默认行为是提交它,因此您必须首先使用event.preventDefault()防止默认行为然后单击按钮后您想要执行的操作(例如:验证等).在您的情况下,您可以调用进行AJAX调用的函数(makeAjaxRequest).您的代码将如下所示:

The default behaviour of a button of type submit in a form is to submit it, so you have to prevent the default behaviour first by using event.preventDefault() and followed by what you desire to do on click of the button (ex: validations etc.). In your case you can call the function that makes the AJAX call (makeAjaxRequest). Your code will look something like this:

$("#signin-login-google-button").click(function(event){
  event.preventDefault();
  makeAjaxRequest();
});
function makeAjaxRequest() {
  $.ajax({
      url: '/connect/google',
      type: 'POST',
      success: function(data){
        //code to open in new window comes here
      }
  });
}

成功执行ajax调用后,您可以编写代码以在新窗口中打开它.您可以参考此答案.

On success of the ajax call you can write code to open it in a new window. You can refer to this answer for the same.

这篇关于javascript:点击按钮进行POST调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆