JavaScript 中的对象覆盖键值对
我正在尝试使用 JavaScript 中的对象来存储用户 ID(密钥)和 GPS 坐标数组,但由于某种原因,每次添加一组新坐标(当它从数据库中提取时)时,它都会覆盖之前的坐标数组(值)中的坐标而不是附加。
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var loc = {};
user_id = data[0];
lati = data[1]; //get id
longi = data[2]; //get name
var myLatlngt = 'new google.maps.LatLng(' + lati + ',' + longi + ')';
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
loc[user_id].push(myLatlngt);
console.log('loc :::', loc);
日志如下:
Resource interpreted as Other but transferred with MIME type undefined.
map2.php:50loc ::: Object
86ad04fb-1da5-4118-8b00-942676d62387: Array[1]
0: "new google.maps.LatLng(51,-82)"
length: 1
__proto__: Array[0]
__proto__: Object
长数字(86ad04...)是用户 ID(密钥),但如果我发送新坐标,它会覆盖而不是附加。如果我能得到任何帮助,我将不胜感激。
谢谢
I'm trying to store a user ID (key) and an array of GPS coordinates using an object in JavaScript, but for some reason each time a new set of coordinates is added (when it pulls from the database), it overwrites the previous coordinates in the array (value) instead of appending.
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var loc = {};
user_id = data[0];
lati = data[1]; //get id
longi = data[2]; //get name
var myLatlngt = 'new google.maps.LatLng(' + lati + ',' + longi + ')';
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
loc[user_id].push(myLatlngt);
console.log('loc :::', loc);
Here's the log:
Resource interpreted as Other but transferred with MIME type undefined.
map2.php:50loc ::: Object
86ad04fb-1da5-4118-8b00-942676d62387: Array[1]
0: "new google.maps.LatLng(51,-82)"
length: 1
__proto__: Array[0]
__proto__: Object
The long number (86ad04...) is the user ID (key), but if I send new coordinates it overwrites instead of appending. I would appreciate any help I can get.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为每次进入函数时都会清空
loc
:Because you empty
loc
every time you enter the function:您需要将
var loc = {};
放置在 ajax 回调之外,以便在多个 ajax 请求中保留其状态。you need to place
var loc = {};
outside of your ajax callback so that its state is preserved over multiple ajax requests.