programing

JavaScript / jQuery로 리디렉션에 POST 데이터를 보내시겠습니까?

new-time 2020. 5. 9. 17:21
반응형

JavaScript / jQuery로 리디렉션에 POST 데이터를 보내시겠습니까? [복제]


이 질문에는 이미 답변이 있습니다.

기본적으로 내가하고 싶은 것은 사용자가 양식을 제출하고 새 페이지로 이동 한 것처럼을

POST

변경할 때 데이터를 보내는 것입니다

window.location

. 숨겨진 URL을 전달해야하기 때문에 이런 식으로해야

GET

하며 미용상의 이유로 단순히 URL에 넣을 수는 없습니다 .이것은 현재 가지고 있지만 POST 데이터를 보내지 않습니다.

if(user has not voted) {

    window.location = 'http://example.com/vote/' + Username;

}

나는 당신이

POST

함께 데이터를 보낼 수 있다는 것을 알고

jQuery.post()

있지만 새로운 데이터와 함께 보내야 합니다

window.location

.그래서 요약하자면, 나는 보내야

api_url

을 통해 값을

POST

http://example.com/vote/

같은 시간에 같은 페이지로 사용자를 보내는 동안.


나중에 참조하기 위해 다음을 수행했습니다

.

if(user has not voted) {

    $('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');

    document.forms['vote'].submit();

}

숨겨진

method=POST action="http://example.com/vote"

양식을 작성하고 작성하여

window.location

전혀 사용하지 않고 제출하십시오 .


@ Kevin-Reid의 답변에 따라, 여기에 "JQuery를 사용하여"양식을 구성하여 양식 개체의 이름을 지정한 다음 다시 조회 할 필요가없는 "다음 결과를 끝내 었습니다"예제에 대한 대안이 있습니다.

var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
  '<input type="text" name="api_url" value="' + Return_URL + '" />' +
  '</form>');
$('body').append(form);
form.submit();

다음은 jQuery를 사용하는 한 어디서나 적용 할 수있는 간단한 작은 함수입니다.

var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            value = value.split('"').join('\"')
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
    }
});

jQuery를 사용 하는 경우 POST 또는 GET 메소드와 함께 작동 하는

리디렉션 플러그인

이 있습니다. 숨겨진 입력이있는 양식을 작성하여 제출합니다. 작동시키는 방법의 예 :

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

참고 :

메소드 유형 GET 또는 POST를 선택적 세 번째 매개 변수로 전달할 수 있습니다. POST가 기본값입니다.


다음은 jQuery를 사용하지 않는 메소드입니다. w3-html-validator에서 현재 페이지를 확인하는 북마크를 만들 때 사용했습니다.

var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

document.body.appendChild(f);
f.submit();

여기에 대한 답변이 혼란 스러울 수 있으므로 작업중 인 샘플 코드를 제공합니다.우선 참조하는 자바 스크립트 windows.location 함수에 POST 매개 변수가 없다는 점에 유의하십시오.그래서 당신은 ...

  1. POST 매개 변수를 사용하여 동적으로 양식을 작성하십시오.
  2. 게시하려는 원하는 값을 가진 텍스트 상자 또는 텍스트 상자를 동적으로 배치
  3. 동적으로 작성한 제출 양식을 호출하십시오.

그리고 예를 들어.

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

모든 것이 잘 되었다면, test2.php로 경로를 재지 정하고 POST를 사용하여 employee_name과 salary의 전달 된 값을 읽을 수 있습니다. 그것은 각각 Peter와 1000이 될 것입니다.

On test2.php you can get your values thus.

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.


Generic function to post any JavaScript object to the given URL.

function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}

This is quite handy to use:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

myRedirect("/yourRedirectingUrl", "arg", "argValue");

var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/

Going to try this and other suggestions for my work.

Is there any other way to do the same ?


You can use target attribute to send form with redirect from iframe. Your form open tag would be something like this:

method="post" action="http://some.url.com/form_action" target="_top"

SOLUTION NO. 1

 //your variable
    var data = "brightcherry";

    //passing the variable into the window.location URL
    window.location.replace("/newpage/page.php?id='"+product_id+"'");

SOLUTION NO. 2

//your variable
var data = "brightcherry";

//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);

details

참고URL : https://stackoverflow.com/questions/8389646/send-post-data-on-redirect-with-javascript-jquery

반응형