의 내가 있다고 가정 해 봅시다 :이에 해당 배열을 설정하는 매끄러운, 빠른 방법을 찾기 위해 노력하고있어Javascript challenge. 배열로 어떻게 이것을 할 수 있습니까?
var directions = [ "name", "start_address", "end_address", "order_date" ];
:
data: { "directions[name]" : directions_name.val(), "directions[start_address]" : directions_start_address.val(), "directions[end_address]" : directions_end_address.val(), "directions[order_date]" : directions_order_date.val() }
주의 패턴. 배열의 이름 "directions"는 값의 접두사입니다. 나는 사람들이이 일을 할 수있는 방법이나 적어도 내가 시도 할 수있는 방법을 제안 할 수있는 방법에 관심이있다.
팁을 주시면 감사하겠습니다.
감사합니다.
편집 ** 지금까지 제안
감사합니다. 그러나 배열 "길 찾기"가 동적이어야한다는 점을 잊어 버렸습니다.
예를 들어, 내가 사용할 수 있습니다
places = ["name", "location"]
그래서 기본적으로
data: { "alpha[blue]" : alpha_blue.val(), "alpha[orange]" : alpha_orange.val() }
를 반환해야
data: { "places[name]" : places_name.val(), "places[location]" : places_location.val() }
alpha = ["blue", "orange"]
을 반환해야 그냥 함수로 배열을 전달할 수 그 데이터 객체를 반환합니다.
var directions = ["name", "start_address", .... ]; var data = someCoolFunction(directions);
희망이 있습니다.
** 편집 * ** * ** * ** * **** 내가 그들의 도움을 모두 감사드립니다
. 나는 다른 길로가는 것을 끝내었다. 그것에 대해 생각한 후에 HTML 양식 자체에 일부 메타 정보를 넣기로 결정했습니다. 그리고, 나는 명명 규칙을 고수한다. 그래서 HTML 폼은 정보를 POST 할 곳을 jQuery에 알려주기 위해 (부 풀리지 않고) 필요한 정보를 가지고있다. 이처럼
// addBox // generic new object box. function addBox(name, options) { var self = this; var title = "Add " + name.charAt(0).toUpperCase() + name.slice(1); var url = name.match(/s$/) ? name.toLowerCase() : name.toLowerCase() + "s"; allFields.val(""); tips.text(""); $("#dialog-form-" + name).dialog($.extend(default_dialog_options, { title: title, buttons: [ { // Add Button text: title, click: function(){ var bValid = true; allFields.removeClass("ui-state-error"); var data = {}; $("#dialog-form-" + name + " input[type=text]").each(function() { // each is fine for small loops :-) var stripped_name = this["name"].replace(name + "_", ""); data[name + "[" + stripped_name + "]"] = $("#dialog-form-" + name + " #" + name + "_" + stripped_name).val(); }); // verify required fields are set $("#dialog-form-" + name + " input[type=text].required").each(function() { bValid = bValid && checkLength($(this), $(this).attr("name").replace("_", " "), 3, 64); }); // find sliders $("#dialog-form-" + name + " .slider").each(function() { data[name + "[" + $(this).attr("data-name") + "]"] = $(this).slider("option", "value"); }); data["trip_id"] = trip_id; if(options != null) { $.extend(data, options); } // add optional key/values if(bValid) { $(".ui-button").attr("disabled", true); $.ajax({ url : "/" + url, type : "POST", data : data }); } } }, { text: "Cancel", click: function(){$(this).dialog("close");} } ] })); }
나는 당신이 무엇을하려고하는지 잘 모르겠다. – xj9
왜 데이터 대신 방향을 사용하지 않겠습니까? like var direction = {name : name.val(), ...} – user347594
전달 된 변수의 이름에 액세스 할 수있는 함수를 작성하는 것은 간단하지 않습니다. http://stackoverflow.com/questions/1009911/javascript -get-argument-value-of-passed-variable-variable –