2014-05-16 39 views
0

我有一个奇怪的JavaScript问题:当我用window.location ...在线上运行带有断点(Firebug)的JavaScript时,我的函数可以正常工作。但是当我将断点取走时,它不再起作用。它的行为就好像它不再执行savePublication()函数一样。Javascript执行正确与断点,但不是没有断点 - 为什么?

有人见过这样的问题吗?这里是我的代码

$("#add").click(function (e) { 

    // Create array with id values of checked checkboxes 
    var idarray = $("input:checked") 
     .map(function() { return $(this).attr("class"); }) //Project classes 
     .get(); //to Array 


    // save each checked publication to database  
    $.each(idarray, function(index, value) { 
     savePublication(value); 
    }); 

    // load new window 
    var uid = $('[name="user_id"]').val(); 
    window.location.href = BASE + '/cv/' + uid+'?panel=accordion_8'; 

}); 

在CAS这是解决问题的重要,这里是功能savePublication()来:

function savePublication(c) { 

    // set variables 
    var author; 
    var title; 
    var year; 
    var subtitle; 
    var user_id = $('[name="user_id"]').val(); 


    // for each element with class = c 
    $("."+c).each(function() { 
     // get element name 
     var attribute = $(this).attr("name"); 

     // get values of attributes and set new variables with values 
     if(attribute === "author") author = htmlspecialchars_decode($(this).text()); 
     if(attribute === "contributor") contributor = $(this).text(); 
     if(attribute === "title") title = $(this).text(); 
     if(attribute === "year") year = $(this).text(); 
    }); 

    // variable joining authors and contributors 
    var authors = author + ", " + contributor; 

    // store data using appropriate route 
    $.post(BASE + '/publication/storeWorldCat', 
       { 
       authors: authors, 
       title:  title, 
       subtitle: "à corriger dans addWorldCat.js", 
       year:  year, 
       user_id: user_id, 
       }, 
    function(data,status){ 
     alert("Data: " + data + "\nStatus: " + status); 
    }); 

感谢您的帮助!

+0

尝试使用'setTimeout(function(){},1000);'让ajax完成其请求 – Reece

+0

它可能是一个时间问题EM。某些元素可能不存在,但由于脚本的中断点足够长。 – Halcyon

+1

@ReeceJHayward有史以来最糟糕的解决方案!哈哈哈 – DontVoteMeDown

回答

1

一旦转到另一页JavaScript停止执行。 您的$.post应该发生了,但取决于$.post需要多长时间,成功可能执行也可能不执行。

放置断点时,$ .post结束并执行成功回调。

您可以变通的作法是要么设置async: false或等待在$。员额:

$.post(BASE + '/publication/storeWorldCat', 
      { 
      authors: authors, 
      title:  title, 
      subtitle: "à corriger dans addWorldCat.js", 
      year:  year, 
      user_id: user_id, 
      }, 
function(data,status){ 
    alert("Data: " + data + "\nStatus: " + status); 
}).done(function() { 
    window.location = "..."; 
}); 

这里看到更多的信息,$.post().done()

0

你可以同步调用您的控制器像这样:

var data = { 
      authors: authors, 
      title:  title, 
      subtitle: "à corriger dans addWorldCat.js", 
      year:  year, 
      user_id: user_id, 
}; 

var success = function(data,status){ 
    alert("Data: " + data + "\nStatus: " + status); 
}); 

$.ajax({ 
    type: 'POST', 
    url: BASE + '/publication/storeWorldCat', 
    data: data, 
    success: success, 
    dataType: dataType, 
    async:false 
});