[英]jquery doesn't work after an ajax call (response in a pop up window)
我有一個帶有表單和一些jquery代碼的jsp頁面。 jQuery代碼可以完美地工作,但是如果我使用ajax調用在彈出窗口中返回該頁面,則jQuery代碼將不再起作用。
我也嘗試使用委派,即:
$('select[name=myElementName]').on("change", function() {
// some code
});
or
$(document).on("change", 'select[name=myElementName]', function() {
// some code
});
代替
$('select[name=myElementName]').change(function() {
// some code
});
Ajax呼叫:
var preview = function () {
$.ajax({
type: "POST",
url: myAction.do,
data: "id=" + myid,
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
return false;
},
error: function () {
return false;
},
});
};
編輯
在Firefox 26.0和Chrome 32.0.x上,我通過使用解決
x.document.close();
后
x.document.write(replace);
相反,在IE上,所有.js包含的腳本都將被忽略(例如jquery-ui-1.9.1.js)。
編輯2
我解決了
<body onload="myload()">
在我的jsp中,我有myload()定義,在其中定義了腳本。
這是因為您正在創建新的DOM結構,但沒有附加事件處理程序。 最簡單的方法是在ajax回調中運行事件處理程序:
$.ajax({
...
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
// now, place the event handler here
$('select[name=myElementName]', x.document.body).change(function() {
// some code
});
}
});
不要使用document.write
它會完全覆蓋編寫時頁面上的所有內容,並導致爭用情況(例如,外部腳本可能已經加載,但也可能沒有加載,從而導致write
順序未知)和腳本加載)。 另外,我相信documnt.write
會將序列化的文本而不是DOM對象放入文檔中,因此它可能不會觸發事件。
相反,您可以打開新窗口,然后直接在其中操作DOM對象(假設它與主頁位於同一服務器上):
//Open a new window for the success info
var newWindow = window.open(newUrl);
//Now grab some element
var someItem = newWindow.document.getElementById( "someId");
//Manipulate dom either by "someItem.innerHTML" or "someItem.appendChild(...)"
如果您要調用AJAX服務器例程並將未在客戶端上進行處理的整個響應放入一個新窗口中,為什么不直接使用該AJAX例程的URL打開窗口並跳過所有內容:
....
var x=window.open(myAction.do + "?id=" + myid,
'_blank',
'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
....
這里唯一的區別是,該請求是GET而不是POST請求,但是數據只是一個id,可以接受嗎?
我的項目中也有類似的問題。 我通過在ajax調用之后編寫成功方法來解決此問題。
{
$.ajax({
type: "POST",
url: "/abc/",
data:{<data>},
async:false,
dataType:'json',
success: function(response)
{
success=1;
Id=response;
return;
}
});
if (success)
{
#your code here
var a='/xyz/?Id='+Id
window.open(a,'_blank');
window.location.href='/registration/'
}
return false;}
而不是使用document.write,而是嘗試在隱藏的DIV中獲取成功數據(記錄到達成功函數中的記錄),然后將其克隆到應該可以使用的彈出窗口中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.