如何获取动态创建表行的Jquery代码,等待AJAX​​调用返回

时间:2012-05-10 20:12:08

标签: jquery ajax dynamic asynchronous wait

所以我的页面上有一个链接"添加发货点"。这会打开一个对话框,让用户输入一些信息..当用户点击" Save Shipping Point"对话关闭,javascript在屏幕上添加一个新行。

问题是,如果用户然后单击动态创建的行上的复选框并单击"删除装运点"该行未被删除。

这是因为创建新行的代码在AJAX调用之前执行,而db update使用正确的id返回。

所以我需要在创建行之前让代码等待id。我在Stack上看到类似的问题,但是调用的语法有点不同,所以我不确定如何将它应用于我的情况。

以下是调用save并创建新行的对话框中的代码。

if (bValid) {
// make Ajax call save the Shipping Point and add to the list
var shipPointId = saveShippingPoint();                  

    // This alert when active does not have the id.
    //alert("Alert3:" + shipPointId);

if (shipPointId == "na") 
    {
        alert("There was a problem adding the Shipping Point.  Please try again.  If the problem persists please contact support.");
} 
    else 
    {
    $j("#shipPoints tr:last").after(
              "<tr>" 
            + "<td>" + city.val().toUpperCase() + ", " + state.val().toUpperCase() + "</td>" 
            + "<td>"
            + "<INPUT type='checkbox' NAME='chk' VALUE='"+ shipPointId + "' />"
            + "<INPUT type='hidden' NAME='shipPointId' VALUE='"+ shipPointId + "' />"
    + "</td>"+ "</tr>");
}
$j(this).dialog("close");
}

这是使AJAX调用save的代码....我在那里放了一个while循环强制等待,就像临时更改一样确认这是问题...循环它等待,并正确创建行。如果没有该函数,则立即将未评估的id返回给调用者,但它不起作用。所以需要知道让它等待的正确方法,以便我得到我需要的行为。

// Ajax call to add the Shipping Point to the Session
function saveShippingPoint() {

    var savedId = "";

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            savedId = xhr.responseText;
        }

    };      
    var url = '<portlet:resourceURL id="saveShippingPoint"/>';
    xhr.open("GET", url + 
       "?city=" + $j( "#city" ).val().toUpperCase() +
       "&state=" + $j( "#state" ).val().toUpperCase() +
       "&stateOther=" + $j( "#stateOther" ).val().toUpperCase() +
       "&zip=" + $j( "#zip" ).val() +
       "&product=" + $j( "#product" ).val().toUpperCase()
       , true);
    xhr.send();

    /* WHile loop just here to test and verify problem */
    while(xhr.readyState != 4) /* null statement */ ;       
    return savedId;
}

提前致谢, -Jim

好的,基于我修改代码的前几条建议,我不使用$ .ajax而是自己操作XmlHttpRequest,并定义成功回调方法。

作为jquery的新手,我在这里明显搞砸了一些语法,因为Add Shipping Point按钮没有关闭而没有添加行......

这是新代码:

$j("#dialog-form").dialog(
{
    autoOpen : false,
    height : 500,
    width : 500,
    modal : true,
    buttons :
    {
        "Add Shipping Point" : function()
        {
            var bValid = true;
            var cityValid = true;
            var stateValid = true;
            var zipPresent = true;
            var zipValid = true;
            updateTips("");
            allFields.removeClass("ui-state-error");
            cityValid = checkRequired(city, "City");
            stateValid = checkRequired(state, "State");
            zipPresent = checkRequired(zip, "Zip");
            if(zipPresent) { zipValid = checkRegexp(zip, /(^\d{5}$)|(^\d{5}-\d{4}$)/, "Zip Code"); }
            bValid = cityValid && stateValid && zipPresent && zipValid;
            if (bValid)
            {
                saveShippingPoint();
                $j(this).dialog("close");
            }
        },
        Cancel : function()
        {
           $j(this).dialog("close");
        }
    },
    close : function()
    {
        allFields.val("").removeClass("ui-state-error");
    }
});
$j("#add-shipping-point").click(function()
{
    $j("#dialog-form").dialog("open");
    return false;
});
});
</script>
<script>
// Ajax call to add the Shipping Point to the Session
function saveShippingPoint()
{
$.ajax(
{
// This is a portal URL....which in reality has no spaces, it just didn't paste in very nicely
url: "/web/secure/!ut/p    /b1/jY7LUoMwGIWfpQ_g5CekGJdRKHek3FrYdCLN0DgUKlBUnl7sxpXo2Z2Z71xQgXIMVAVMASjao6Lho6z4INuG19--0A7xo51uEs1x9Sx- AntNrMAgBMBUZiCfAUUJXd81FaDPAGD7DnYjfa0A4P_l4Rcx- Cu_Q8UNWXpwAxYmAqs9C5TP2P3PVOJjHWxPswjoRAWKUYL2QA7xK30bjsb79bOcQiC0n_pqPMKH46bt4DUvnke7bFKzNGNbFuhGNLHVar6ZL5fvOt3164UKOr5KOKTvFxkU4WtbAa0LXl5Ep4YRR3ySqBzUW8e7DtznBj7Ao0UMN4!/" +
"?city=" + $j( "#city" ).val().toUpperCase() +
"&state=" + $j( "#state" ).val().toUpperCase() +
"&stateOther=" + $j( "#stateOther" ).val().toUpperCase() +
"&zip=" + $j( "#zip" ).val() +
"&product=" + $j( "#product" ).val().toUpperCase() ,
type: 'GET',
cache: false,
timeout: 30000,
success: function(data)
{
$j("#shipPoints tr:last").after(
"<tr>"
+ "<td>"
+ city.val().toUpperCase()
+ ", "
+ state.val().toUpperCase()
+ "</td>"
+ "<td>"
+ "<INPUT type='checkbox' NAME='chk' VALUE='"+ data + "' />"
+ "<INPUT type='hidden' NAME='shipPointId' VALUE='"+ data + "' />"
+ "</td>"
+ "</tr>");
}
});
return;
};
</script> 

2 个答案:

答案 0 :(得分:1)

更改saveShippingPoint函数以使用jQuery Ajax函数(而不是自己构造和使用xhr对象),然后实现成功回调以更新表。

答案 1 :(得分:0)

查看jQuery的deferred对象。