2016-11-22 25 views
0

jQueryデータを投稿してURLを変数として渡さずに同じファイルで受信するにはどうすればよいですか(たとえばtest.php?data=xxx)。同じファイルにjQuery変数を投稿してPHPで受信

たとえば、コンソールログに表示されるresponse.dataは次のとおりです。

function (response) {      
    console.log(response.data); 
}, 

このデータを送信して同じファイルで受信したいとします。

function (response) {      
    //console.log(response.data); 
    $.post(window.location.href, {json_data: response.data}); 
}, 

が、同じファイルのボディに、私は

print_r($_POST); 

を印刷するとき、それは何も表示されませんが:私は、次の試してみました。

+0

ここにあなたがコンソールに表示response.dataで持っている値を追加してください。私はこれをテストすると、$ _POST ['json_data']がうまく見えるようになっていますが、response.dataのある場所に簡単な値を入れています。 – WEBjuju

答えて

1

response.dataがタイプであることを確認してください:PlainObjectまたは文字列PlainObjects

UPDATE

Here is a video that describes what this code sample does.

コードサンプルの詳細はこちらをご覧ください

<?php 
    if (empty($_POST)) : 
    ?> 
     Nothing was posted, please click there \/<br><br> 
    <?php 
    else : 
    echo 'You posted: '.print_r($_POST['json_data'], 1).'<br><br>'; 
    endif; 
?> 

<a href="javascript:" onclick="fake_simple_response('simple string');">click here (simple string)</a><br> 
<a href="javascript:" onclick="fake_simple_response({cat:'meow', dog:'woof'});">click here (plain object)</a> 


<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<script> 
function fake_simple_response (response) { 
    console.log(response); 
    $.post(window.location.href, {json_data: response}); 
} 
</script> 
+0

あなたはあなたがテストしたことを書いており、それは動作します。あなたは完全な例を投稿できますか? – sam

+0

確かに私は今私の答えを更新しています。 – WEBjuju

+0

ビデオに感謝します。 – sam

0

POSTを使用する場合、1つの方法は、フォームを作成してjQueryで送信することです。

<form id="form-id" method="post" action=""> 
    <input type="hidden" value="hello world" /> 
</form> 

<script> 
$('#form-id').submit(); 
</script>