1

在 javascript 程序中,我试图从文件中的数据填充全局 3 属性数组对象。该程序没有成功运行,所以我尝试调试,但发现它在使用 Firefox 的内部调试器运行时确实有效。所以尝试使用 Firebug,但 Firebug 冻结了。回到简单的“警报”插入,我发现添加“警报”会产生成功的运行,但会出现令人费解的“警报”消息 - 数组长度在数组创建子例程内似乎没问题,但在例程之外为零。大概我做错了什么,但mm对这种行为感到困惑,所以转向这里寻求帮助(作为第一次用户)。FWIW JQuery 被用来读取数据。以下是该程序的要点:

var nodedata = new Array();
nodedata = [];
// use routine to fill array
requestNodeData();
alert('POST requestNodeData nodedata.length=' + nodedata.length);
// create markers
for (var index in nodedata) addMarker(nodedata[index], index);
alert('POST index Loop nodedata.length=' + nodedata.length);
  ...

function requestNodeData() {
  var formData = $('#form').serialize();
  $.post('/cgi-bin/get_nodedata.cgi', formData, processNodeData, 'text').error(processNodeDataError);
  return false; // this prevents form button submission
}

function processNodeData(data) {
  var strings = new Array(3);
  datalines = data.split(/\n/);
  for (var i = 0; i < (datalines.length); i++) {
    strings = datalines[i].split(/,/);
    nodedata[i] = {
      'lat': strings[0],
      'lng': strings[1],
      'name': strings[2]
    };
  }
  alert('END OF requestNodeData nodedata.length=' + nodedata.length);
}

注意:“END OF requestNodeData”警报总是给出预期的数组大小添加“POST requestNodeData”警报使程序成功运行!但数组大小是“0”,而不是预期的数组大小!?如果省略“POST requestNodeData”警报,则“POST index Loop”给出 0,但在包含该警报时给出预期的数组大小

4

2 回答 2

1

You are using an AJAX request to retrieve the data. This request is, by default, asynchronous. What happens, is that you are executing requestNodeData(). This sets up the ajax request and sends it to the server. The script will immediately continue however and handle the data that it gets back from the ajax request async from the rest of the script.

Long story short. It'll execute:

requestNodeData();
for (var index in nodedata) addMarker(nodedata[index], index);

... (some time goes by) ...

and when the data from requestNodeData is ready,
it'll execute processNodeData(data)

The use of alert will pause the script (but apparently not the ajax request), which will 'just in time' fill in your variable. For this reason, it's usually better to use console.log to prevent alerts disrupting the flow of your application.


To fix this use the jQuery.ajax() method instead of jQuery.post() and set 'async' to false, like so:

$.ajax({
  type: "POST",
  url: '/cgi-bin/get_nodedata.cgi',
  data: formData,
  success: processNodeData,
  dataType: 'text',
  async: false
});

This will cause the script to execute the script 'in order'.

于 2013-07-11T19:10:18.457 回答
0

Ajax 请求是异步的,所以你不能在调用之后处理它的结果。警报“帮助”您,只是因为它在执行之后暂停所有内容,并且在此期间,ajax 成功结束,end 填充了您的变量。所以你应该对你的节点数据做任何工作,只是在成功回调中

于 2013-07-11T19:04:41.703 回答