简体   繁体   English

Golang + ajax 发布数据

[英]Golang + ajax post data

I've got a page with a number of fields, not in a form setup because I wanna be able to act on them individually and post with ajax.我有一个包含多个字段的页面,而不是在表单设置中,因为我希望能够单独对它们进行操作并使用 ajax 发布。 I am using Go to process the post data.我正在使用 Go 来处理发布数据。 However, it seems to post multiple times because in my Go code I am outputting a post variable to the console to test, and it dumps the output 5 times, which represents the number of variables in the post data.但是,它似乎发布了多次,因为在我的 Go 代码中,我将一个 post 变量输出到控制台进行测试,并且它将输出转储 5 次,这表示 post 数据中的变量数。 I also had this type of behavior when I just used a jquery alert to show the post data.当我只使用 jquery 警报来显示发布数据时,我也有这种类型的行为。 Am I misunderstanding something about how ajax posts, or is there some other bug going on?我是不是对 ajax 发布方式有误解,还是有其他错误?

Go code去代码

func addProduct(w http.ResponseWriter, r *http.Request, p httprouter.Params) {

              frmCategory:=r.PostFormValue("category")
              fmt.Println(frmCategory)
}

func main() {

          router:=httprouter.New()
          router.POST("/addProduct",addProduct)

}

AJAX code AJAX 代码

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js" type="text/javascript"></script>

    <!-- <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script> -->

    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel='stylesheet' type='text/css'>

var postData="bcode\="+ $('#bCodeID').val()+"&category\="+$("#selected_category").val()+"&price\="+priceModifier+"&description\="+$('#itemDescription').val()+"&colorcode\="+$('#SelectedColorCode').val();

$.ajax({

        url: '/addProduct',
        type: 'post',
        dataType: 'text',
        data : postData,
        success : function(data) {
              $('#warningBox').modal({
                  show: false
              });
        }
});

Console output控制台输出

Toys

Toys

Toys

Toys

Toys

Toys

Toys

I found the bug.我发现了这个错误。 Earlier I was experimenting with not allowing clicks outside of a modal dialog, and was using $(document).click(function () { ... } wrapped around all my jscript code. Once I removed that, everything else fixed itself.早些时候,我尝试不允许在模态对话框之外点击,并使用 $(document).click(function () { ... } 包裹了我所有的 jscript 代码。一旦我删除了它,其他一切都会自行修复。

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

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