2014-11-23 37 views
1

我正在編寫一個web應用程序,並且必須從多個API中獲取數據才能顯示該用戶。所以在第一步中,用戶可以從第一個API中選擇幾個地方。在那裏我得到了像1.2345,6.7890這樣的座標,並將它們保存到一個數組中。現在我想將它們傳遞給路由API,參數必須是http://example.com/route?location=1.2345,6.7890&location=2.3456,7.8901jQuery ajax停止數據urlencode

問題是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不要編碼我的數據字符串?

+0

最糟糕的情況是,您可以手動構建查詢字符串,而不是將對象傳遞給'data' – charlietfl 2014-11-23 23:56:04

回答

0

根據上面的註釋,您必須手動編寫輸入字符串,因爲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, 
 
});

0

是的,它似乎是在不同的瀏覽器(Firefox不編碼而Chrome一樣)不同了urlencoded 。嘗試將座標直接映射到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" 
});