为什么数组不会通过ajax调用发送? [英] Why the array will not send through the ajax call?

查看:80
本文介绍了为什么数组不会通过ajax调用发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Ajax代码中,我正在向go lang api发送一个关联数组,但是go lang不会接收任何数组.为什么?

In my ajax code I'm sending an associative array to the go lang api but go lang would not receiving any array. Why?

for (var i = 1; i <= optionsArr; i++) {
    span_arr.push({
        day       : valueSelected,
        time_slug : i,
        timing    : $("#"+i).text(),
        count     : $('#select_count'+i).val()
    });
}
console.log(span_arr[1].time_slug);
$.ajax({
    url:"/api/v1/provider_spot",
    type:"POST",
    data:{span_arr:span_arr},
    dataType:"json",
    success:function(response){
        console.log(response);
    }
});

为什么这个ajax不会将数组发送到go api?在下面的mvc结构中,我想要接收此数据:

Why this ajax will not sending the array to the go api? Here in go lang following mvc structure I want to receiving this data:

 Route{"SaveProviderSpot", "POST", "/provider_spot", controller.SaveProviderSpot},

 func SaveProviderSpot(c *gin.Context) {
   fmt.Println(c.PostForm("span_arr"))
 }

推荐答案

由于双方的数组定义可能不同,因此无法将数组直接从客户端发送到服务器.

You can not send an array directly from client to server,due to the array definition may not be the same in both sides.

两种解决方法:

a.您可以在clinet中将数组转换为json字符串,然后将其作为字符串参数发送到服务器,在服务器端,您可以对其进行解析并将其转换为数组

a. You can convert the array into a json string in the clinet,then send it to server as a string parameter,in the server side,you can parse it and convert it to array

b.迭代数组,并使用一些特殊字符将其转换为字符串,还作为字符串参数传递给服务器,示例如下:

b. Iterate the array,and convert it to a string using some special characters,also pass to server as string parameter,an example is as below:

var dataStr = "";
for (var i = 1; i <= optionsArr; i++) {
    //each array element split with 3 semicolons,and each property in element split with 2 semicolons
    dataStr += valueSelected + ";;" + i + ";;" + $("#"+i).text() 
           + ";;" + $('#select_count'+i).val() + ";;;";
}
$.ajax({
    url:"/api/v1/provider_spot",
    type:"POST",
    data:{dataStr:dataStr},
    dataType:"json",
    success:function(response){
        console.log(response);
    }
});
//now it is correct

这篇关于为什么数组不会通过ajax调用发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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