如果我有一个变量需要发布到 PHP 脚本而不刷新页面。 这可能吗?如果是这样,怎么办?
我使用 jQuery 的尝试:
$.ajax({
url: "myphpfile.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
}
})
我如何接收在我的 php 脚本中传递的数组?
最佳答案
使用GM_xmlhttpRequest()
允许跨域帖子(在大多数情况下都是如此)。
油猴脚本:
// ==UserScript==
// @name _Sending arbitrary data, demo
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
var someArray = [1, 2, 3];
var serializedData = JSON.stringify (someArray);
GM_xmlhttpRequest ( {
method: "POST",
url: "http://SERVER.COM/PATH/ShowJSON_PostedData.php",
data: serializedData,
headers: {"Content-Type": "application/json"},
onload: function (response) {
console.log (response.responseText);
}
} );
ShowJSON_PostedData.php:
<?php
echo '<title>JSON data</title>';
echo '<h2>JSON post data:</h2><pre>';
$jsonData = json_decode($HTTP_RAW_POST_DATA);
print_r ($jsonData);
echo '</pre>';
?>
控制台。将显示:
<title>JSON data</title><h2>JSON post data:</h2><pre>Array
(
[0] => 1
[1] => 2
[2] => 3
)
</pre>
关于php - 如何将 javascript 数据发送到 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13808001/