简体   繁体   English

POST适用于警报消息,但并非没有警报消息

[英]POST works with alert message but doesn't without it

I am making a post request to google app script with the code below 我正在使用以下代码向Google应用程序脚本发出发布请求

    var url ="MY WEBAPP EXEC"

     function submitForm() {
        var postRequest = {}
        postRequest.name = $("#inputName").val();
        postRequest.email = $("#inputEmail1").val();
        postRequest.message = $("#inputMessage").val();

        alert(JSON.stringify(postRequest));  // this alert

        $.post(url, postRequest, function(data,status){
           alert('success')
        });
    }

I am very confused why the post is working with the alert but doesn't work without it. 我很困惑,为什么帖子会与警报一起工作,但没有警报就无法工作。 Thank you. 谢谢。

=== OK I guess my question was not clear enough sorry. ===好吧,我想我的问题还不够清楚,对不起。

I have a form accessing GAS remotely. 我有一个远程访问GAS的表单。 I assumed the url implied that I was accessing GAS remotely. 我以为该URL暗示我正在远程访问GAS。 At the moment I am working on my localhost and on my JS above it works if the alert statement is present and does not do anything if alert is not there. 目前,我正在本地主机和上面的JS上工作,如果存在alert语句,则可以正常工作;如果没有alert,则不执行任何操作。

I was watching the execution list on GSuite Developer Hub to see if the request failed or completed. 我正在GSuite开发人员中心上查看执行列表,以查看请求是否失败或完成。 I observed if the alert statement is in the script the execution status is completed but if the alert statement is not there nothing happens. 我观察到警报语句是否在脚本中,执行状态已完成,但是如果警报语句不存在,则什么也不会发生。 I assume that my post script is not working if alert is not there. 我假设如果没有警报,我的帖子脚本将不起作用。 Any idea why? 知道为什么吗?

You haven't shown exactly how that function is called, but it's likely to be because, if this is truly a "form submit" action, the result of submitting a form is to "load a new page" (which can be the same page you're on, and is so by default with no action attribute in the form tag 您尚未确切显示该函数的调用方式,但这可能是因为,如果这确实是一个“表单提交”操作,则提交表单的结果就是“加载新页面”(可以相同)。页面所在的页面,默认情况下是这样,在form标记中没有action属性

Since you want to perform AJAX on form submit, you need to "prevent" the "default" form submit action - this can be achieved as shown in the second and third lines below 由于您要对表单提交执行AJAX,因此需要“防止”“默认”表单提交操作-可以实现,如下面的第二行和第三行所示

 var url ="MY WEBAPP EXEC"
 function submitForm(e) { // if this function is called using an event handler, it gets an event as the first and only argument
    e.preventDefault(); // prevent the "default" form submit action
    var postRequest = {}
    postRequest.name = $("#inputName").val();
    postRequest.email = $("#inputEmail1").val();
    postRequest.message = $("#inputMessage").val();

    alert(JSON.stringify(postRequest));  // this alert

    $.post(url, postRequest, function(data,status){
       alert('success')
    });
}

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

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