![](/img/trans.png)
[英]Post Variable and Array from JQuery to PHP in same $ajax request
[英]Post jQuery variable on same file and receive with PHP
我該如何發布jQuery數據並在不通過URL傳遞作為變量的情況下,在同一文件上接收(例如test.php?data=xxx
)。
例如,這是我可以在控制台日志中看到的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);
它不顯示任何內容。
確保response.data是Type: PlainObject或String 。 在PlainObjects上查看更多信息
更新
代碼樣例
<?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>
如果要使用POST,一種方法是創建一個表單並使用jQuery提交。
<form id="form-id" method="post" action="">
<input type="hidden" value="hello world" />
</form>
<script>
$('#form-id').submit();
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.