JQuery ajax stop urlencode of data

JQuery ajax stop urlencode of data

本文关键字:of data urlencode stop ajax JQuery      更新时间:2023-09-26

我正在编写一个Web应用程序,必须从多个API获取数据以向用户显示。因此,在第一步中,用户可以选择我从第一个 API 获得的几个位置。在那里,我得到像 1.2345,6.7890 这样的坐标,并将它们保存到一个数组中。现在我想将它们传递给路由 api,并且必须 http://example.com/route?location=1.2345,6.7890&location=2.3456,7.8901 参数。

问题是 jQuery 对数据进行编码并将 切换到 %2C。Google-API 接受两个版本,但我必须使用的 API 只接受 、 。

myPlaces = ["1.2345,6.7890", "2.3456,7.8901"]
$.ajax({
    url : "example.com",
    datatype : "json",
    jsonp : "jsonp",
    data : {
        loc : myPlaces
    }
});

如何告诉 jQuery 不要对我的数据字符串进行编码?

根据上面的评论,您必须手动编写输入字符串,因为 jQuery 的参数序列化将始终自动对您的逗号进行 URL 编码。

幸运的是,这不应该太令人头疼:

myPlaces = ["1.2345,6.7890", "2.3456,7.8901"];
//string composition function
var placesString = myPlaces.reduce(function(str, current){
  return str + "loc=" + current;
}, "");
    
//then use it in your ajax call
$.ajax({
    url : "example.com",
    datatype : "json",
    jsonp : "jsonp",
    data : placesString,
});

是的,它在不同的浏览器中似乎有不同的编码(Firefox 不编码,但 Chrome 编码)。尝试将坐标直接映射到 url 中:

myPlaces = ["1.2345,6.7890", "2.3456,7.8901"];
var myPlacesQueryString = "";
$.each(myPlaces, function(i, value) {
    myPlacesQueryString += "location=" + value;
    if (i < myPlaces.length - 1) {
        myPlacesQueryString += "&";
    }
});
$.ajax({
    url : "example.com/route?" + myPlacesQueryString,
    datatype : "json",
    jsonp : "jsonp"
});