2014-12-10 3 views
0

하나의 필드 만 포함하는 양식이있는 HTML 페이지가 있습니다. 제출은 실제로 페이지 새로 고침을 수행하지 않고 로컬 JavaScript 처리를 수행합니다.URL에서 양식을 채우십시오.

위대한 작품이지만 한 가지 단점이 있습니다. 양식을 미리 제출 한 URL (예 : http://example.com/myform?field=val)을 누군가에게 줄 수는 없습니다.

URL에 ?field=[val]이 포함되어있는 경우로드시 fieldval으로 채우고 자바 스크립트 제출 작업을 수행한다고 jQuery에 알릴 수 있습니까?

(당신은뿐만 아니라 역으로이 작업을 수행 할 수 있습니다 경우 보너스 포인트 : 제출하면, 페이지를 새로 고침하지 않고, http://example.com/myform에서 http://example.com/myform?field=[val]에 위치 표시 줄의 URL을 변경)

답변

1

안된를하지만,이 같은 아마 뭔가 :

// Setup a document ready to run on initial load 
$(document).ready(function() { 
    var urlParams = getUrlParams() 
     , form; 

    // Only proceed if there are URL params 
    // Note this assumes that all URL params are valid input fields in your form, that they have been decoded, and that all the fields you need are there. Adjust accordingly. 
    if (urlParams) { 
     form = $('#your_form'); 
     $.each(urlParams, function(value, field) { 
      form.find('input[name="' + field + '"]').val(value); 
     }); 

     // Trigger your event listener 
     form.submit(); 
    } 
}); 

가능하면 getUrlParams function의 시작 지점을 확인하십시오.

0

답변이 있습니다.

$(document).ready(function(){ 
    var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b 
    var query = r.exec(window.location.href); //gets the first query from the url 
    while (query != null) { 

      //index 0=whole match, index 1=first group(key) index 2=second group(value) 
     $("input[name="+ query[1] +"]").attr("value",query[2]); 

     query = r.exec(window.location.href); //repeats to get next capture 

    } 



//handles when someone clicks a input button with id submit 
$('#submit').click(function(){ 

    var url = window.location.pathname + "?"; 
    $("input[name]").each(function(){ 
     if (this.value) //if the forms have values 
     url += $(this).attr('name') + "=" + this.value + "&"; //appends the name and value 
    }); 
    history.replaceState("hstory", "", url.substring(0, url.length - 1)); //changes the url without reloading and removes last & 
    }); 

}); 

첫 번째 부분은 사용자가 제출의 ID와 버튼을 칠 때 제 핸들이 URL에 값을 재 로딩하는 동안, 지정된 URL 값으로 가져오고 양식 입력에 삽입 처리한다.

관련 문제