如何在javascript中使Inline表达式在执行前等待

时间:2012-07-05 17:53:41

标签: c# javascript asp.net ajax eval

我有一个表达式<%= GetAddPinScript() %>来评估我的代码隐藏文件中的方法。该方法生成javascript,然后返回: AddPushpin('data', 'more data', numbers, numbers, 'no');

这里的关键是'no'是由代码隐藏方法插入的变量,并帮助我的其他javascript确定是否应该显示某些内容。(基本上是一个bool)

我遇到的问题是我的代码隐藏中的方法需要一个变量(在下面的代码中为result),该变量是通过ajax调用发送之前表达式进行评估,以确定在javascript中生成的正确变量 - 但表达式始终评估页面加载。

那么如何在进行ajax调用之前阻止表达式的计算呢?

的Javascript

function displayGeneralInfo(specifics)
     {
     var callback = AddQueryString(window.location.href, "action", "displayResults");
     $.ajax({
            url: callback,
            type: "POST",
            async: false,
            data: {
                specifics: specifics
                }
                });
                <%= GetAddPinScript() %>
     }

和AddPushpin函数

function AddPushpin(name, description, latitude, longitude, selected) {
    // Add a pin to the map
    var center = new Microsoft.Maps.Location(latitude, longitude);
    var pin = new Microsoft.Maps.Pushpin(center, null);

    if(selected !== null || selected!="")
      {
      if(selected == "yes")
       {
       infoboxOptions = new Microsoft.Maps.Infobox(center,
        {                          width: 285,
                               height: 170,
                               visible:true,
                               actions:[{label: 'Associate', eventHandler: associate}]
                               });
                               map.entities.push(infoboxOptions);
        }
    }
    map.entities.push(pin);
}

和代码隐藏代码段

public string GetAddPinScript()
    {
foreach (Location location in foo(x => !string.IsNullOrWhiteSpace(x.Longitude) && !string.IsNullOrWhiteSpace(x.Latitude)))
        {
            selected = "no";
            if (!result.IsNullOrEmpty())
            {
                if (location.MapPinDescription.IndexOf(result) > 0)
                    selected = "yes";
            }
            pins.Add(string.Format("AddPushpin('{0}', '{1}', {2}, {3}, '{4}');",
                location.etc1("'", @"\'"), location.etc2("'", @"\'"), location.etc3, location.etc4, selected));
           string retVal = string.Join("\n", pins.ToArray());
           return retVal;

2 个答案:

答案 0 :(得分:0)

要在ajax调用完成后运行add pin脚本,您应该将其设置为ajax调用的完整处理程序:

function displayGeneralInfo(specifics)
 {
 var callback = AddQueryString(window.location.href, "action", "displayResults");
 $.ajax({
        url: callback,
        type: "POST",
        async: false,
        data: {
            specifics: specifics
            }
            },
        complete:  <%= GetAddPinScript() %>
 });

请注意,上述语法假定GetAddPinScript将返回一个函数,即现有函数的名称或匿名函数块。

答案 1 :(得分:0)

你不能让它等待。 javascript在客户端上执行,此功能在服务器上运行。 Asp.net在将数据发送到客户端之前完成所有绑定,因此您无法说等到某些代码在客户端上运行然后运行此函数。我建议你在对服务器进行ajax调用时调用这个函数。从此函数返回一些html,然后将其包含在成功函数的html中。