Programing

자바 스크립트를 사용하여 게시 요청 매개 변수를 읽는 방법

lottogame 2020. 10. 16. 07:01
반응형

자바 스크립트를 사용하여 게시 요청 매개 변수를 읽는 방법


내 html에서 게시 요청 매개 변수를 읽으려고합니다. 자바 스크립트에서 다음 코드를 사용하여 get 요청 매개 변수를 읽을 수 있습니다.

$wnd.location.search

그러나 포스트 요청에는 작동하지 않습니다. 누구나 javascript를 사용하여 내 html에서 post request 매개 변수 값을 읽는 방법을 알려줄 수 있습니까?


POST 데이터는 서버 측에서 처리되는 데이터입니다 . 그리고 Javascript는 클라이언트 측에 있습니다. 따라서 JavaScript를 사용하여 게시물 데이터를 읽을 수있는 방법이 없습니다.


서버가 JavaScript 변수를 채우도록하는 PHP의 작은 부분은 빠르고 쉽습니다.

var my_javascript_variable = <?php echo $_POST['my_post'] ?>;

그런 다음 일반적인 방법으로 JavaScript 변수에 액세스하십시오.


JavaScript는 클라이언트 측 스크립팅 언어로, 모든 코드가 웹 사용자의 컴퓨터에서 실행됩니다. 반면에 POST 변수는 서버로 이동하여 거기에 상주합니다. 브라우저는 이러한 변수를 JavaScript 환경에 제공하지 않으며 개발자는 이러한 변수가 마술처럼 거기에있을 것이라고 기 대해서는 안됩니다.

브라우저는 JavaScript가 POST 데이터에 액세스하는 것을 허용하지 않기 때문에 PHP와 같은 외부 행위자가 POST 값을 스크립트 변수 또는 전송중인 POST 값을 캡처하는 확장 / addon으로 에코하지 않고 POST 변수를 읽는 것은 거의 불가능합니다. GET 변수는 클라이언트 컴퓨터에서 구문 분석 할 수있는 URL에 있기 때문에 해결 방법을 통해 사용할 수 있습니다.


sessionStorage를 사용하십시오!

$(function(){
    $('form').submit{
       document.sessionStorage["form-data"] =  $('this').serialize();
       document.location.href = 'another-page.html';
    }
});

another-page.html에서 :

var formData = document.sessionStorage["form-data"];

참조 링크-https: //developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage


전달하려는 값을 설정하기 위해 localStorage 또는 다른 방법을 사용하지 않는 이유는 무엇입니까?

이렇게하면 어디서든 액세스 할 수 있습니다!

하여 어디서든 내 말은 주어진 도메인 / 컨텍스트 내에서


POST는 브라우저가 클라이언트 (브라우저)에서 웹 서버로 보내는 것입니다. 게시 데이터는 http 헤더를 통해 서버로 전송되며 서버 끝 또는 클라이언트 (브라우저)에서 웹 서버로의 경로 (예 : 프록시 서버) 사이에서만 사용할 수 있습니다. 따라서 JavaScript와 같은 클라이언트 측 스크립트에서 처리 할 수 ​​없습니다. CGI, PHP, Java 등과 같은 서버 측 스크립트를 통해 처리해야합니다. 여전히 JavaScript로 작성해야하는 경우 Node.js와 같은 서버에서 JavaScript를 이해하고 실행하는 웹 서버가 있어야합니다.


jQuery-PostCapture ( @ ssut / jQuery-PostCapture )를 사용 하여 게시 요청 매개 변수를 읽을 수 있습니다 .

PostCapture 플러그인은 몇 가지 트릭으로 구성됩니다.

제출 버튼을 클릭하면 onsubmit이벤트가 전달됩니다.

이때 PostCapture는 양식 데이터를 직렬화하고 html5 localStorage (사용 가능한 경우) 또는 쿠키 저장소에 저장합니다.


Java / REST API로 작업하는 경우 해결 방법은 쉽습니다. JSP 페이지에서 다음을 수행 할 수 있습니다.

    <%
    String action = request.getParameter("action");
    String postData = request.getParameter("dataInput");
    %>
    <script>
        var doAction = "<% out.print(action); %>";
        var postData = "<% out.print(postData); %>";
        window.alert(doAction + " " + postData);
    </script>

먼저 PHP를 통해 게시물 변수를 인코딩하기 위해 'json_encode'를 사용할 수 있습니다. 그런 다음 JSON 인코딩 된 포스트 변수에서 JS 객체 (배열)를 생성합니다. 그런 다음 JavaScript 루프를 사용하여 해당 변수를 조작합니다. 다음과 같이-아래이 예제에서-HTML 양식 양식을 채 웁니다.

<script>

    <?php $post_vars_json_encode =  json_encode($this->input->post()); ?>

    // SET POST VALUES OBJECT/ARRAY
    var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
    console.log(post_value_Arr);

    // POPULATE FIELDS BASED ON POST VALUES
    for(var key in post_value_Arr){// Loop post variables array

        if(document.getElementById(key)){// Field Exists
            console.log("found post_value_Arr key form field = "+key);
            document.getElementById(key).value = post_value_Arr[key];
        }
    }


</script>

한 가지 옵션은 PHP에서 쿠키를 설정하는 것입니다.

예 : 1 일 후 만료 값이있는 유효하지 않은 이름의 쿠키 $invalid:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

그런 다음 JS에서 다시 읽습니다 ( JS 쿠키 플러그인 사용).

var invalid = Cookies.get('invalid');

if(invalid !== undefined) {
    Cookies.remove('invalid');
}

이제 invalidJavaScript 변수에서 값에 액세스 할 수 있습니다 .


It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language. So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}

And therefrom use post['key'] = newVal; etc...


POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.

SITE A: has a form submit to an external URL (site B) using POST SITE B: will receive the visitor but with only GET variables


function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");

$(function(){
    $('form').sumbit{
        $('this').serialize();
    }
});

In jQuery, the above code would give you the URL string with POST parameters in the URL. It's not impossible to extract the POST parameters.

To use jQuery, you need to include the jQuery library. Use the following for that:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>

We can collect the form params submitted using POST with using serialize concept.

Try this:

$('form').serialize(); 

Just enclose it alert, it displays all the parameters including hidden.


<head><script>var xxx = ${params.xxx}</script></head>

Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

참고URL : https://stackoverflow.com/questions/1409013/how-to-read-the-post-request-parameters-using-javascript

반응형