jQuery - 将 AJAX 返回关联到特定 DIV

发布于 2024-11-30 10:48:07 字数 2858 浏览 1 评论 0 原文

我正在尝试创建一个能够对多个请求进行排队的运行列表。我可以发出单个请求并将返回值附加到正确的 DIV 中。但是当我发出两个或多个请求时,在第一个请求返回之前,第一个 GET 被网络服务器丢弃(项目限制...),第二个返回被插入到第一个请求的 DIV 中。

编辑:我想确保相关请求被附加到正确的 DIV 中。如果 GET 请求被网络服务器终止,那么我将在 error:{textStatus} 设置上添加一个函数,并将库存文本附加到 div 中,提醒用户错误。

我正在使用 jQuery 插件“Transform”。

JS:

<script type="text/javascript">
    $(function() {
        var evtIncrmt = 0
        $("#searchForm").submit(function (event) { 
            event.preventDefault();
            evtIncrmt = evtIncrmt + 1

            var $form = $(this),
                //term = $form.find('input[name="cmdtextbox"]').val(),
                url = $form.attr('action');
                cmdInput = "<M ID=\"Input_MSGID\"><R ID=\"AscString_RECID\">OPD</R></M>"

            $( "#listContainer" ).prepend( $(document.createElement( "div" ))
                .attr({ id: evtIncrmt + "entry",  title: "photo by a cohen" })
                .text( "This is Event Number " + evtIncrmt )
            );
            $( "#" + evtIncrmt + "entry" ).append( $(document.createElement( "div" ))
                .attr({ id: evtIncrmt + "entryXmlReturn",  title: "review by w mitchell" })
                .text(  "Waiting for response. . " )
            );
            console.log("event increment before ajax call" + evtIncrmt);
            $.ajax({
                type: "GET",
                timeout: 120000,  /* 2mins */
                context: "#" + evtIncrmt + "entryXmlReturn",
                url: url,
                data: { 
                    XMLString: cmdInput ,
                    uqid: evtIncrmt
                },
                dataType: "text",
                success: function (xmlReturn) {
                    console.log("event increment inside transform" + evtIncrmt);
                    $( "#" + evtIncrmt + "entryXmlReturn" ).transform({
                        xmlstr: xmlReturn,
                        xsl: { url: "xsl/StaticStyle.xsl" }
                    });
                }
            });
        });
    });
</script>

html:

<html>
    <body>
        <div class="links">
            <form action="/" id="searchForm">
                <input type="input" name="cmdtextbox" value="OPD" />
                <input type="submit" value="Search" />
            </form>
        </div>
        <div id="loadHTMLajax"></div>
        <div id="listContainer">
            <div id="2staticEntry">This is entry two.</div>
            <div id="1staticEntry">Hello oldest entry number ONE</div>
        </div>
    </body>
</html>

除了没有按预期工作之外,我确信我在创建此功能时没有使用最佳实践。如果您发现代码可以写得更好的地方,请随时批评。

这是我向 stackoverflow 社区提出的第一个问题,大家好,感谢多年来我从该资源中获得的所有匿名使用。

I am trying to make a running list with the ability to queue up multiple requests. I'm able to make single request and have the return be append to the correct DIV. But when I make two or more requests, before the first request is returned, the first GET is discarded by the webserver (project constraints...), and the second return is inserted into the first request's DIV.

EDIT: I'd like to ensure the related request gets appended into the correct DIV. If the GET request is terminated by the webserver, then I'll add a function on the error:{textStatus} setting and append stock text into the div alerting the user of the error.

I'm using the jQuery plugin "Transform".

JS:

<script type="text/javascript">
    $(function() {
        var evtIncrmt = 0
        $("#searchForm").submit(function (event) { 
            event.preventDefault();
            evtIncrmt = evtIncrmt + 1

            var $form = $(this),
                //term = $form.find('input[name="cmdtextbox"]').val(),
                url = $form.attr('action');
                cmdInput = "<M ID=\"Input_MSGID\"><R ID=\"AscString_RECID\">OPD</R></M>"

            $( "#listContainer" ).prepend( $(document.createElement( "div" ))
                .attr({ id: evtIncrmt + "entry",  title: "photo by a cohen" })
                .text( "This is Event Number " + evtIncrmt )
            );
            $( "#" + evtIncrmt + "entry" ).append( $(document.createElement( "div" ))
                .attr({ id: evtIncrmt + "entryXmlReturn",  title: "review by w mitchell" })
                .text(  "Waiting for response. . " )
            );
            console.log("event increment before ajax call" + evtIncrmt);
            $.ajax({
                type: "GET",
                timeout: 120000,  /* 2mins */
                context: "#" + evtIncrmt + "entryXmlReturn",
                url: url,
                data: { 
                    XMLString: cmdInput ,
                    uqid: evtIncrmt
                },
                dataType: "text",
                success: function (xmlReturn) {
                    console.log("event increment inside transform" + evtIncrmt);
                    $( "#" + evtIncrmt + "entryXmlReturn" ).transform({
                        xmlstr: xmlReturn,
                        xsl: { url: "xsl/StaticStyle.xsl" }
                    });
                }
            });
        });
    });
</script>

html:

<html>
    <body>
        <div class="links">
            <form action="/" id="searchForm">
                <input type="input" name="cmdtextbox" value="OPD" />
                <input type="submit" value="Search" />
            </form>
        </div>
        <div id="loadHTMLajax"></div>
        <div id="listContainer">
            <div id="2staticEntry">This is entry two.</div>
            <div id="1staticEntry">Hello oldest entry number ONE</div>
        </div>
    </body>
</html>

Along with not working as intended, I'm sure I didn't use best practices while making this function. If you see areas where the code could be better written, please feel free to criticize.

This is my first question to the stackoverflow community, so hello, and thanks for all the anon usage I've gotten out of this resource over the years.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幸福还没到 2024-12-07 10:48:07

可能是因为你根本没有增加变量 evtIncrmtl 假设当你说请求失败时它涉及到成功函数。

顺便说一句,这里存在不同的硬依赖关系,你的响应将始终遵循不正确的特定顺序。可能存在这样的情况:您发送 1,2,3 个请求,响应顺序将为 2,3 和 1,即使 1 和 2 是失败的请求..因此这种方法有点不正确..

正确的方法是将 div 的 id(或 div 号)发送到您的服务器,然后您将相同的 id 作为响应的一部分发回。由于您的数据类型是文本,您可以通过将其更改为“json”来简单地实现此目的(从谷歌研究 abt json 作为您的服务器端脚本语言)并且您的响应应如下所示:

{
"divId": "2staticEntry",  //"divCount" :2 //divid or its equivalent
xmlReturn: "<your old txt>"
}

现在解析此 json.. 在 js 中读取 abt 解析 json。最简单的方法是使用 eval() 但我不推荐它..

一旦解析它,您就可以使用它返回的对象,如下所示:

var obj= eval(respnse);  //or equivalent 
obj.divId   //represents your div to be updated
$( "#" + evtIncrmt + "entryXmlReturn" ).transform({
                        xmlstr: obj.xmlReturn,
                        xsl: { url: "xsl/StaticStyle.xsl" }
                    });

希望这是有道理的..

probably cos you are not incrementing the varible evtIncrmtl at all assuming when you say the request has failed it comes to the success function..

btw there is a vary hard dependency in here that your responses will always follow a particular order which is incorrect.. there might be a case where in you send 1,2,3 requests and the response order will be 2,3 and 1 even though 1 and 2 are failed requests.. thus this approach is kinda incorrect..

the correct appraoch would be to send in the id of the div (or the div no) to your server and you send back the same id as part of your response.. since your datatype is text you can simply achieve this by changing it to "json" (research abt json from google for your server side scripting language) and your response should be as follows:

{
"divId": "2staticEntry",  //"divCount" :2 //divid or its equivalent
xmlReturn: "<your old txt>"
}

now parse this json.. read abt parsing json in js. easiest way is to use eval() but I wouldnt recommend it..

once you parse it you can use the object returned by it as follows:

var obj= eval(respnse);  //or equivalent 
obj.divId   //represents your div to be updated
$( "#" + evtIncrmt + "entryXmlReturn" ).transform({
                        xmlstr: obj.xmlReturn,
                        xsl: { url: "xsl/StaticStyle.xsl" }
                    });

hope that made sense..

绾颜 2024-12-07 10:48:07

Zzzz,感谢您的投入。它把我推向了正确的方向。我重新评估了获取 XML 数据的方式。事实证明,当 .transform 函数本身执行 AJAX 调用时,我正在对 .transform 函数进行 AJAX 调用。通过在单独的函数中调用它,并且无法在两个 ajax 方法之间传递调用的唯一 id,我失去了引用。仅使用转换方法,当页面收到来自网络服务器的返回时,我可以保持分配的完整性。

以下是更正后的代码;下面的代码摘要:

//code above unchanged
console.log("event increment before ajax call" + evtIncrmt);

$("#" + evtIncrmt + "entryXmlReturn").transform({
    //async:false,
    success: function () {
        alert("Transform succeeded");
    },
    xml: {
        url: "/",
        data: { 
            XMLString: cmdInput ,
            uqid: evtIncrmt
        },
        //timeout: 120000  /* 2mins */
        success: function () {
            console.log("xml " + evtIncrmt + ' succeeded');
        }
    },
    xsl: {
        url: "xsl/StaticStyle.xsl",
        success: function () {
            console.log("xsl " + evtIncrmt + ' succeeded');
        }
    }
});

我仍然对对网络服务器进行多次调用有问题。但我决定使用一个队列,因为我实际上一次只能发出一个请求,并且线性地进行每个 AJAX 调用。

如果我让它工作,我可以用编码队列函数回复,但我不知道这里的礼仪,因为它会有点偏离主题......

我引用 stackoverflow 答案: 如何将 javascript 函数存储在队列...

Zzzz, thanks for your input. It nudged me in the right direction. I re-evaluated how I was fetching the XML data. It turns out I was making the AJAX call for the .transform func, when it performs the AJAX call itself. By calling it in a seperate func, and not being able to pass the unique id of the call between the two ajax methods, I lost reference. Using just the transform method, I can maintain assignment integrity when the page receives its return from the webserver.

Below is the corrected code; summary below code:

//code above unchanged
console.log("event increment before ajax call" + evtIncrmt);

$("#" + evtIncrmt + "entryXmlReturn").transform({
    //async:false,
    success: function () {
        alert("Transform succeeded");
    },
    xml: {
        url: "/",
        data: { 
            XMLString: cmdInput ,
            uqid: evtIncrmt
        },
        //timeout: 120000  /* 2mins */
        success: function () {
            console.log("xml " + evtIncrmt + ' succeeded');
        }
    },
    xsl: {
        url: "xsl/StaticStyle.xsl",
        success: function () {
            console.log("xsl " + evtIncrmt + ' succeeded');
        }
    }
});

I still have issue with multiple calls made to the webserver. But I've decided to employ a queue, since I really can only make one request at a time, and make each AJAX call linearly.

If I get it working, I can reply with the coded queue func, but I don't know etiquette here for that, since it would be slightly off-topic...

I'm referencing stackoverflow answer: How do I store javascript functions in a queue...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文