main page

Javascript를 이용해서 다음 페이지에 파라미터 넘기기 위한 방법이다.

<html>
 <head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  <script>
   function setChildValue(index) {
    window.location.href = "subPage.html?index=" + index;
   }
  </script>
 </head>
 <body>
  <button onclick="setChildValue(123)">Click me</button>
 </body>
</html>

sub page

방법 1

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function () {
			var val = location.href.substr(
				location.href.lastIndexOf('=') + 1
			);
			console.log('val : ' + val);
		});
	</script>
</head>
<body>

</body>
</html>

방법 2

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		function getURLParameter(name) {
			return decodeURI(
			 (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
			);
		}

		function getURLParameter2(name) {
			 return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
		}
		$(document).ready(function () {
			console.log('val : ' + getURLParameter('index'));
			console.log('val : ' + getURLParameter2('index'));
		}
	</script>
</head>
<body>
</body>
</html>

방법 3

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		var getParameter = function (param) {
			var returnValue;
			var url = location.href;
			var parameters = (url.slice(url.indexOf('?') + 1, url.length)).split('&');
			for (var i = 0; i < parameters.length; i++) {
				var varName = parameters[i].split('=')[0];
				if (varName.toUpperCase() == param.toUpperCase()) {
					returnValue = parameters[i].split('=')[1];
					return decodeURIComponent(returnValue);
				}
			}
		};
		$(document).ready(function () {
			console.log('val : ' + getParameter('index'));
		}
	</script>
</head>
<body>
</body>
</html>

문제점

다음과 같이 ajax로 다른 페이지에 접급하려할 때 에러가 발생하였다.

source

$.ajax(
 {
  type: "GET",
  contentType: 'text/xml',
  dataType: "xml",
  url: 'url address',
  timeout: 4000,
  async: false,
  success: parseXml,
 });

error message

XMLHttpRequest cannot load http://xx.xx.xx.xx/xxx. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

원인은 ajax로 외부 서버에 접속하려 할 경우에 보안상의 문제 때문이라고 한다. 해결방법에는 여러가지가 있다.


해결방안

이것저것 며칠을 찾아보면서 찾은 각종 해결방법은 아래와 같다.

  1. PHP
    header("Access-Control-Allow-Origin: *");
  2. JSP
    <% response.addHeader("Access-Control-Allow-Origin", "*"); %>
  3. ajax
    dataType의 값을 jsonp로 변경한다.
    $.ajax(
     {
      type: "GET",
      contentType: 'text/xml',
      dataType: "jsonp",
      url: 'url address',
      //timeout: 4000,
      async: false,
      success: parseXml,
     });
  4. open source
    homepagegithub
  5. With jQuery and the Google AJAX Feed API
    $.ajax({
      url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
      dataType : 'json',
      success  : function (data) {
        if (data.responseData.feed && data.responseData.feed.entries) {
          $.each(data.responseData.feed.entries, function (i, e) {
            console.log("------------------------");
            console.log("title      : " + e.title);
            console.log("author     : " + e.author);
            console.log("description: " + e.description);
          });
        }
      }
    });



var str = 'abc1';

str.replace(/A/gi, 'b');

//결과값 : str = bbc1


▣ replace(바꿀 문자, 바꾸어질 문자) 

바꿀문자에 정규식 사용이 가능하다.


▣ 자바스크립트에서의 정규식 

var test = /패턴/flage;

→ flage 부분

g(Global) : 패턴에 맞는 모든 문자 검색

i(Ignorecase) =  대/소문자 구분하지 않는다.

m(Multilinem) : 여러줄을 검색한다.


+ Recent posts