그래서 제목에서 말하는 것처럼 고객을 업데이트하거나 생성 할 모달 대화 상자를 정의하는 방법을 알아 내려고합니다. 그리고 주문 페이지 나 다른 페이지에서 간단히 호출하여 보여줄 수 있습니다.
저는 JavaScript를 처음 접했지만 프로그래밍에는 익숙하지 않습니다. Windows 앱에서 호출하여 사용자에게 보여줄 수있는 클래스를 만들었지 만 js에서 어떻게해야할지 모르겠습니다.
div 및 iframe과 함께 모달 대화 상자를 사용하는 방법을 알아 냈지만 여러 페이지에서 사용할 수있게 만드는 것이 저를 피했습니다.
도와주세요, 감사합니다, 데이브
편집 : 페이지에서 대화 상자로, 그리고 다시 필드에 액세스 할 수 있기를 원하기 때문에 iframe을 사용하고 싶지 않습니다.
편집 2 : 그래서 (이것이 처음임을 기억하십시오) ... 메인 페이지 (default.aspx)와 고객 페이지 (customer.html) 및 고객 단일 인스턴스 모듈 (customer.js)을 만들었습니다. default.aspx에서 고객 모듈을로드하고 내가 만든 "로드 된"사용자 지정 이벤트에 대한 이벤트 처리기를 추가하면 작동하고 양식에 데이터가로드됩니다. 그런 다음 고객 대화 상자를 열면 작동하고 대화 상자는 고객 모듈에서 자체 데이터를로드하지만 대화 상자에서 저장 버튼을 클릭하면 데이터가 제대로 저장되지만 저장 후 고객 모듈이 "데이터 저장 됨"이벤트를 발생시키고 default.aspx에서 잡히지 않습니다 ...
이것에 잘못된 것이 보이나요 ?? 이 웹 사이트는 내가 여기에 붙여 넣을 수있는 것에 대해 까다 롭기 때문에 뭔가 놓친 경우 알려주십시오 ...
default.aspx
<script type="text/javascript">
var customer;
var customerDialog;
function showCustomerPopup(closedCallback) {
var width = $(window).innerWidth;
if (width > 420)
width = 420;
$('#divCustomerPopup').remove();
$("body").append("<div id='divCustomerPopup' style='display: none;'></div>");
var divPopup = $("#divCustomerPopup");
$.get("templates/customer.html", function (data) {
divPopup.html(data);
});
customerDialog = $("#divCustomerPopup").dialog({
autoOpen: true,
height: 300,
width: width,
modal: true,
});
}
$(function () {
var custIDField = $("#CustomerID");
customer = Customer.getInstance();
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
$('#CustomerName').on('change', function () {
showCustomerPopup();
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
addCustomer();
});
$(customer).on("dataloaded", function (e, data) {
console.log("dataloaded");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
});
$(customer).on("datasaved", function (e, data) {
console.log("datasaved");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
customerDialog.dialog('close');
});
});
customer.js
<script type="text/javascript">
var Customer = (함수 () {var 인스턴스;
function init() {
var dr = {};
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
var event = jQuery.Event("ajaxerror")
event.data = msg
$(instance).trigger(event);
if (msg.contains("login") > 0) {
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
}
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
};
function WebServerCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("dataloaded");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented())
refreshForm();
};
function WebServerSaveCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("datasaved");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented()) {
refreshForm();
}
};
function NewCustomer() {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'-1'}")
};
function LoadCustomer(CustomerID) {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'" + CustomerID + "'}")
};
function refreshForm() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
$('#customer-CustomerID').val(dr.CustomerID);
$('#customer-CustomerName').val(dr.CustomerName);
$('#customer-CustomerSince').val(new Date(dr.CustomerSince).toDateInputValue());
checkBoxCheck($('#customer-VIP'), dr.VIP);
checkBoxCheck($('#customer-OnHold'), dr.OnHold);
checkBoxCheck($('#customer-Tax1Exempt'), dr.Tax1Exempt);
checkBoxCheck($('#customer-Tax2Exempt'), dr.Tax2Exempt);
$('#customer-OnHoldReason').val(dr.OnHoldReason);
$('#customer-PrimaryContactID').val(dr.PrimaryContactID);
$('#customer-DefaultEmployeeID').val(dr.DefaultEmployeeID);
$('#customer-Phone1').val(dr.Phone1);
$('#customer-Phone2').val(dr.Phone2);
$('#customer-Address1').val(dr.Address1);
$('#customer-Address2').val(dr.Address2);
$('#customer-Address3').val(dr.Address3);
$('#customer-City').val(dr.City);
$('#customer-Province').val(dr.Province);
$('#customer-Country').val(dr.Country);
$('#customer-PostalCode').val(dr.PostalCode);
$('#customer-Description').val(dr.Description);
};
function refreshDR() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
dr.CustomerID = $('#customer-CustomerID').val();
dr.CustomerName = $('#customer-CustomerName').val();
dr.CustomerSince = new Date($('#customer-CustomerSince').val());
dr.VIP = checkBoxCheck($('#customer-VIP'));
dr.OnHold = checkBoxCheck($('#customer-OnHold'));
dr.Tax1Exempt = checkBoxCheck($('#customer-Tax1Exempt'));
dr.Tax2Exempt = checkBoxCheck($('#customer-Tax2Exempt'));
dr.OnHoldReason = $('#customer-OnHoldReason').val();
dr.PrimaryContactID = $('#customer-PrimaryContactID').val();
dr.DefaultEmployeeID = $('#customer-DefaultEmployeeID').val();
dr.Phone1 = $('#customer-Phone1').val();
dr.Phone2 = $('#customer-Phone2').val();
dr.Address1 = $('#customer-Address1').val();
dr.Address2 = $('#customer-Address2').val();
dr.Address3 = $('#customer-Address3').val();
dr.City = $('#customer-City').val();
dr.Province = $('#customer-Province').val();
dr.Country = $('#customer-Country').val();
dr.PostalCode = $('#customer-PostalCode').val();
dr.Description = $('#customer-Description').val();
};
function SaveCustomer() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
var data = "{'CustomerID':'" + $("#customer-CustomerID").val() + "','json':'" + JSON.stringify(dr) + "'}";
WebServerCall("UpdateCustomerData", WebServerSaveCallback, FailedCallback, data)
};
return {
datarow: function () { return dr; },
create: NewCustomer,
load: LoadCustomer,
save: SaveCustomer,
loadData: refreshDR,
loadForm: refreshForm
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
}) ();
Customer.html
<div class="ui-corner-all fieldcontainer">
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerName">Name:</label>
<input class="ui-corner-all " type="text" id="customer-CustomerName" />
<input type="hidden" id="customer-CustomerID" />
</div>
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerSince">Since:</label>
<input class="ui-corner-all " type="date" id="customer-CustomerSince" />
<input class="ui-corner-all " type="checkbox" id="customer-VIP" title="VIP" />
<label class="ui-corner-all" for="customer-VIP">VIP</label>
</div>
<div class="ui-corner-all fielddiv">
<input class="ui-corner-all " type="checkbox" id="customer-OnHold" title="On Hold" />
<label class="ui-corner-all" for="customer-OnHold">On Hold</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax1Exempt" title="GST Exempt" />
<label class="ui-corner-all" for="customer-Tax1Exempt">GST Exempt</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax2Exempt" title="PST Exempt" />
<label class="ui-corner-all" for="customer-Tax2Exempt">PST Exempt</label>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-OnHoldReason">On Hold/Acct:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-OnHoldReason"></textarea>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PrimaryContactID">Primary Contact:</label>
<select id="customer-PrimaryContactID" class="ui-corner-all "></select>
<input type="button" id="customer-NewContact" class="ui-corner-all " value="New Contact" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-DefaultEmployeeID">Default Employee:</label>
<select id="customer-DefaultEmployeeID" class="ui-corner-all "></select>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone1">Phone 1:</label>
<input class="ui-corner-all " type="text" id="customer-Phone1" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone2">Phone 2:</label>
<input class="ui-corner-all " type="text" id="customer-Phone2" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Address1">Address 1:</label>
<input class="ui-corner-all " type="text" id="customer-Address1" /><br />
<label class="ui-corner-all " for="customer-Address2">Address 2:</label>
<input class="ui-corner-all " type="text" id="customer-Address2" /><br />
<label class="ui-corner-all " for="customer-Address3">Address 3:</label>
<input class="ui-corner-all " type="text" id="customer-Address3" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-City">City:</label>
<input class="ui-corner-all " type="text" id="customer-City" /><br />
<label class="ui-corner-all " for="customer-Province">Province:</label>
<input class="ui-corner-all " type="text" id="customer-Province" /><br />
<label class="ui-corner-all " for="customer-Country">Country:</label>
<input class="ui-corner-all " type="text" id="customer-Country" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PostalCode">PostalCode:</label>
<input class="ui-corner-all " type="text" id="customer-PostalCode" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Description">Description:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-Description"></textarea>
</div>
<div style="width: 100%; text-align:center;">
<input class="ui-corner-all " id="customer-Submit" type="submit" value="Create" /> <input class="ui-corner-all " id="customer-Cancel" type="button" value="Cancel" />
</div>
</div>
<script type="text/javascript" src="../common.js"></script>
<script type="text/javascript" src="../Customer.js"></script>
<script type="text/javascript" >
var custIDField = $('#customer-CustomerID');
var customer; // dataloaded, datasaved events passing dr
var employees;
var contacts;
function getEmployeesCallback(rawresult) {
employees = jQuery.parseJSON(rawresult.d);
loadEmployeesDropDown();
};
function loadEmployeesDropDown() {
var ddl = $("#customer-DefaultEmployeeID");
ddl.empty();
$.each(employees, function (i, item) {
var option = $('<option>').val(item.EmployeeID).text(item.EmployeeName);
if (item.EmployeeID == customer.datarow().EmployeeID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
function getContactsCallback(rawresult) {
contacts = jQuery.parseJSON(rawresult.d);
loadContactsDropDown();
};
function loadContactsDropDown() {
var ddl = $("#customer-PrimaryContactID");
ddl.empty();
$.each(contacts, function (i, item) {
var option = $('<option>').val(item.ContactID).text(item.ContactName);
if (item.ContactID == customer.datarow().PrimaryContactID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
$(function () {
customer = Customer.getInstance();
if (customer.datarow().CustomerID == undefined) {
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
}
// customer.loadForm();
$(customer).on("ajaxerror", function (msg) {
//alert("Ajax Error " + msg);
});
$(customer).on("dataloaded", function (e, data) {
customer.loadForm();
//contacts
if (contacts == undefined) {
var withid = -1;
if (customer.datarow().CustomerID != undefined) {
if (customer.datarow().CustomerID > 0) {
withid = customer.datarow().CustomerID;
}
}
if (withid != -1) {
WebServerCall("GetCustomerContacts", getContactsCallback, FailedCallback, "{'CustomerID':'" + customer.datarow().CustomerID + "'}");
} else {
WebServerCall("GetContacts", getContactsCallback, FailedCallback);
}
} else {
loadContactsDropDown();
}
});
$(customer).on("datasaved", function (e, data) {
alert("Customer " + data.CustomerID + " has been saved.");
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
customer.loadData();
customer.save();
});
$("#customer-Cancel").on("click", function (e) {
e.preventDefault();
customer.load($("#customer-CustomerID").val());
});
//employees
if (employees == undefined) {
WebServerCall("GetEmployees", getEmployeesCallback, FailedCallback);
} else {
loadEmployeesDropDown();
}
});
</script>
</form>
common.js
`var webserviceBaseUrl = '/WebService.asmx/';
var websiteBaseUrl = '/';
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, str, startIndex) !== -1;
};
}
if (!('contains' in Array.prototype)) {
Array.prototype.contains = function (arr, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, arr, startIndex) !== -1;
};
}
Date.prototype.toDateTimeLocal = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
var hour = now.getHours();
var min = now.getMinutes();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
if (hour < 10)
hour = "0" + hour;
if (min < 10)
min = "0" + min;
var today = now.getFullYear() + '-' + month + '-' + day + 'T' + hour + ':' + min;
return today;
});
Date.prototype.toDateInputValue = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
return today;
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function checkBoxCheck(checkBox, checked) {
if(checked){
if (checked == 'true') {
checkBox.attr('checked', 'checked');
return true;
} else {
checkBox.removeAttr('checked');
return false;
}
} else {
if (checkBox.attr('checked') == 'checked') {
return true;
} else {
return false;
}
}
}
function WebServerCall(functionName, successCallback, failedCallback, datatoSend) {
$.ajax({
type: "POST",
url: webserviceBaseUrl + functionName,
data: datatoSend,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successCallback,
error: failedCallback,
failure: failedCallback
});
}
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
alert(msg);
if (msg.contains("login") > 0)
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
}
`
그래서 많은 학습 후 (이 튜토리얼은 매우 유용했습니다 : https://code.tutsplus.com/courses/30-days-to-learn-jquery ) 그리고 많은 노력을 기울여 결국 작동하게 만들었습니다 ... 문제는 그러나 이것이 내가 전에 찾을 수 있었으면하는 것입니다.
이것은 "네임 스페이스"를 사용하여 기능적 단일 인스턴스 "클래스"(클래스, 플러그인 또는 모듈이 아닌 것으로 생각되는 것이 더 나은 용어 임)를 만드는 방법을 보여줍니다.
var 네임 스페이스를 이벤트 "대상"으로 사용하는 것이 매우 편리하다는 것을 알았습니다.
어떻게 생각해?
파일 : test.js
var XMen = {
Customer: (function($, undefined) {
var instance;
var datarow = {};
function init() {
function privateLoadData(idNumber) {
//Load up data
datarow = {IDField: idNumber, ValueField: 'something'};
$(XMen).trigger('XMen.CustomerDataLoaded');
};
function privateDisplay() {
console.log(datarow);
$(XMen).trigger('XMen.CustomerDataDisplayed');
};
return {
dr: function() { return datarow; }, //needs to be wrapped in function to get changes
load: privateLoadData,
display: privateDisplay
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
})(jQuery),
SalesOrder: (function($, undefined) { // another one like above? })(jQuery)
}
그런 다음이 파일을 페이지에 포함합니다.
파일 : test.html
<body>
<h1>testing</h1>
<div id="testing"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
var customer = XMen.Customer.getInstance();
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test - XMen.CustomerDataLoaded");//, e, data);
})
console.log("test - Loading 8");
customer.load(8);
console.log("test - loading test2.html");
$("#testing").load("test2.html", function () {
console.log("test - finished loading test2.html");
});
setTimeout(function () {
console.log("test - displaying customer...");
customer.display();
}, 2000);
})(jQuery);
</script>
test2.html에는 이미 test.html에 포함되어 있으므로 스크립트를 포함하지 않습니다.
파일 : test2.html
<div id="test2">
<h1>This is test2.html</h1>
<button id="btnTest">Test</button>
</div>
<script>
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test2 - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test2 - XMen.CustomerDataLoaded");//, e, data);
})
})(jQuery);
console.log("test2 - displaying customer...");
customer.display();
</script>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다