相同的 Ajax 调用了两次..JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/950037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:13:29  来源:igfitidea点击:

Same Ajax called twice..JQuery

jqueryajax

提问by useranon

i have a question in JQuery..I m using $.ajax()in my code (Function 1)to send the fieldname and the sequence number to the ctrller which gets its data by $_POST['name']and $_POST['sequenceno']and updates the fieldname in the table with sequence no given..And generates the Preview Display Panel with the inserted fields .. Now I'm trying the change the field name again tat is Now when I click on the generated display panel fields, the corresponding settings will open and i will try to change the name of the field now(Function 2)

我有使用JQuery..I米一个问题$.ajax()在我的代码(Function 1)发送字段名和序列号,其通过获取其数据的ctrller$_POST['name']$_POST['sequenceno']并且与序列表中没有given..And生成预览显示面板更新字段名与插入的字段.. 现在我正在尝试再次更改字段名称 现在当我单击生成的显示面板字段时,相应的设置将打开,我将尝试立即更改字段名称(Function 2)

Both Function1and Function2are same ..In the Function1I'm sending the fieldname and the sequence no

无论Function1Function2相同..In了Function1我送的字段名和顺序没有

In the Funciton 2,i want to send the same fieldname and (but the other value)sequenceno..

在功能 2 中,我想发送相同的字段名和(但另一个值)序列号..

But in Function1 (sequenceno is the counter value) Whereas in the Function2 (sequenceno is the clicked div id (display Panel))

但是在 Function1 中(sequenceno 是计数器值)而在 Function2 中(sequenceno 是点击的 div id(显示面板))

How can i make use of the same func for both ..Or could i need to use separate funcs..

我如何才能为两者使用相同的 func ..或者我是否需要使用单独的 funcs..

Even i tried with 2 separate funcs with different urls but not updated correctly

即使我尝试使用 2 个不同 url 的独立函数,但没有正确更新

My code is

我的代码是

    //This is what i insert the field initially

              $(".TextFieldSettings #fieldTitle").change(function (){
             fieldname=$(".TextFieldSettings #fieldTitle").val();
    $.ajax({
           type: "POST",
           url: "./server",
        data: "name="+fieldname+"&sequenceno="+counter,

                success: function(msg){
                      }//success
           });//ajax

     });//change

//After inserting to get the updated values in JSON format

     var htm = $.ajax({
       type: "GET",
          url: "./viewforms",
         async: false
       }).responseText;
        var myObject = eval('(' + htm + ')');


    gettype=myObject.attributes[0]["type"];
   getlabel=myObject.attributes[0]["labels"];

    //showing in my DisplayPanel view

            $("#labelstr"+counter+"").html(getlabel);
     });//change

Now When i click the DisplayPanel view

现在当我单击 DisplayPanel 视图时

      $("#displayPanel div").live("click", function(){
                             div_id=$(this).attr("id");

                                var htm = $.ajax({
                                  type: "GET",
                                  url: "./getattributes/"+div_id+"",
                                  async: false
                                 }).responseText;
                                var myObject = eval('(' + htm + ')');


                                gettype=myObject.attributes[0]["type"];
                                getlabel=myObject.attributes[0]["labels"];
                                getsize=myObject.attributes[0]["size"];

    if(gettype=='Text')
     {
    $(".TextFieldSettings").show(function(){
    $(".TextFieldSettings #fieldTitle").val(getlabel);//showing the updated value
                             if(getsize=='100')
                           {
             $("#fieldSize option:contains(Small)").attr("selected",true);
                           }
                             else if(getsize=='200')
                            {
        $("#fieldSize option:contains(Medium)").attr("selected",true);
                         }
              else 
            {
          $("#fieldSize option:contains(Large)").attr("selected",true);
            }
//Again i m changing the fieldname


       $(".TextFieldSettings #fieldTitle").change(function (){
      fieldname=$(".TextFieldSettings #fieldTitle").val();


                                alert(div_id);
                                        $.ajax({
                                           type: "POST",
                                           url: "./editsettings",



                                                                         data: "name="+fieldname+"&sequenceno="+div_id,
                                           success: function(msg){

                                            }//success
                                           });//ajax


});//change in text value later*/



                    });//show
                    }//if type = TEXT

                });//displaypanel Div clicked

But now if I try to change the fieldname again I'm writing another POST function editsettingsbut the execution comes inside Func1(changing initially) instead of Func2(changing in the fieldname again)... Please anyone get out the answer for this.... Note: $(".TextFieldSettings #fieldTitle").change()is used twice inside my prg ..May be because of this the updation goes wrong

但是现在,如果我再次尝试更改字段名称,我正在编写另一个 POST 函数,editsettings但执行会在内部Func1(最初更改)而不是Func2(再次更改字段名称)......请任何人为此找到答案......注意: $(".TextFieldSettings #fieldTitle").change()在我的 prg 中使用了两次..可能是因为这个更新出错了

采纳答案by Rytmis

It seems like the problem is that both of your event handlers are firing, and you only want the latter one to fire.

问题似乎是您的两个事件处理程序都在触发,而您只希望后者触发。

The jQuery .change() function addsan event handler to the change event. It doesn't replace existing ones. If you want to remove the previous handler, you need something like:

jQuery .change() 函数为 change 事件添加了一个事件处理程序。它不会取代现有的。如果要删除以前的处理程序,则需要以下内容:

$(".TextFieldSettings #fieldTitle").unbind('change') 

before you attach a new handler.

在附加新处理程序之前。

please note that I'm not sure this works (I just found it from the api docs) and I can't test it right now. However, the general idea is that if you want an event handler to stop responding to an event, you have to remove the handler.

请注意,我不确定这是否有效(我刚刚从 api 文档中找到它)并且我现在无法对其进行测试。但是,一般的想法是,如果您希望事件处理程序停止响应事件,则必须删除该处理程序。

回答by Stofkn

Are you sure you are not including the same script twice? For example:

您确定没有两次包含相同的脚本吗?例如:

Viewstart:

视图开始:

Scripts/jquery-1.6.1.js

Partial view:

部分观点:

<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>

I got the same problem and I solved it by deleting the min-version.

我遇到了同样的问题,我通过删除最小版本来解决它。

I hope this will help.

我希望这将有所帮助。

回答by dr.emi

I have another case. I got twice send post ajax when bind click a button. It caused by I have two id that has same name, so the trigger detected twice.

我还有一个案例。当绑定单击按钮时,我两次发送 post ajax。这是因为我有两个同名的 id,所以触发器检测到两次。

回答by cicidi

I am working on a project which is using Amazon web service EC2. I am uploading a large file (up to 150 MB). Use Ajax on the front end. And spring MVC on backend. My problem is Spring controller "uploadFile()" method called twice. I set a breakpoint in my javascript, javacript method does not called twice. This only happen on AWS instance, not on my local. And it is around 90 second between uploadFile() method call. Then the ajax callback get error. Statuscode= 0, error ="" Firefox Firebug says "aborted" Chrome inspect gives me "net::ERR_EMPTY_RESPONSE"

我正在开发一个使用 Amazon Web 服务 EC2 的项目。我正在上传一个大文件(最大 150 MB)。在前端使用 Ajax。和后端的spring MVC。我的问题是 Spring 控制器“uploadFile()”方法被调用了两次。我在我的 javascript 中设置了一个断点,javacript 方法没有调用两次。这仅发生在 AWS 实例上,而不发生在我的本地。并且在 uploadFile() 方法调用之间大约是 90 秒。然后ajax回调得到错误。Statuscode= 0, error ="" Firefox Firebug 说“中止” Chrome 检查给我“net::ERR_EMPTY_RESPONSE”

I though it might be some where ajax call backend twice.

我认为这可能是 ajax 调用后端两次的地方。

I search many solution on stackoverflow. like
1. /add e.preventDefault() and e.stopImmediatePropagation(); 2 ./or change maxSwallowSize in tomcat/confg/server.xml 3. $("#uploadFileForm").unbind('submit').submit(function (e) 4. change async to true and add timeout value to ajax method type: 'POST', timeout: 60000, async: true,

我在 stackoverflow 上搜索了许多解决方案。像
1. /add e.preventDefault() 和 e.stopImmediatePropagation(); 2 ./或更改 tomcat/confg/server.xml 中的 maxSwallowSize 3. $("#uploadFileForm").unbind('submit').submit(function (e) 4. 将 async 更改为 true 并将超时值添加到 ajax 方法类型:'POST',超时:60000,异步:真,

None of above work.

以上都没有工作。

Finaly I soltion it by change idle timeout in ELB to 600 second. And my controller does not called twice.

最后,我通过将 ELB 中的空闲超时更改为 600 秒来解决它。而且我的控制器没有调用两次。

http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-idle-timeout.htmlhttps://aws.amazon.com/blogs/aws/elb-idle-timeout-control/

http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-idle-timeout.html https://aws.amazon.com/blogs/aws/elb-idle-timeout-control/

First I want to thanks to all the people who answer question on stackoverflow, which help a lot , a lot, a lot. The solutions are not wrong , just not to my case. And This issue take me 3 days. I hope it can help you question. "ajax fire/ call twice" "Spring controller call twice" "Ajax timeout"

首先我要感谢所有在 stackoverflow 上回答问题的人,他们帮助了很多,很多,很多。解决方案没有错,只是不适合我的情况。而这个问题需要我 3 天。希望可以帮到你提问。“ajax 触发/调用两次”“Spring 控制器调用两次”“Ajax 超时”