我正在尝试从JavaScript中检索此数据 speedMbps 。使用Ajax将数据发布到我的PHP代码,但我没有得到任何输出。我是ajax的新手,只使用ajax进行自动完成。
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!
var imageAddr = "testimage.jpg";
var downloadSize = 2097152; //bytes
window.onload = function() {
var oProgress = document.getElementById("progress");
oProgress.innerHTML = "Loading the image, please wait...";
window.setTimeout(MeasureConnectionSpeed, 1);
};
function MeasureConnectionSpeed() {
var oProgress = document.getElementById("progress");
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
download.onerror = function (err, msg) {
oProgress.innerHTML = "Invalid image, or error downloading";
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
oProgress.innerHTML = "Your connection speed is: <br />" +
speedBps + " bps<br />" +
speedKbps + " kbps<br />" +
speedMbps + " Mbps<br />";
$.ajax({
method: "POST",
url: "test_select.php",
data: {speedMbps: speedMbps },
cache: false
}).done(function( html ) {
$( "#speed" ).val( html );
});
}
}
</script>
<input type="text" id="speed" name="speed" value="">
test_select.php
<?php
echo $_POST['speedMbps'];
if(isset($_POST['speedMbps'])){
echo $speedMbps = $_POST['speedMbps'];
}
?>
答案 0 :(得分:0)
$.ajax({
type: "POST",
url: "test_select.php",
data: {speedMbps: speedMbps },
cache: false
}).done(function( html ) {
$( "#results" ).val( html );
});
将method:"POST"
更改为type:"POST"
。
答案 1 :(得分:-1)
您可能希望合并顶部的底部脚本并将其放在jquery挂钩之后因为变量。
此外,您在我的Ajax脚本中缺少method: "POST"
。这是指定HTTP请求类型所必需的,因为在.php文件中使用$ _POST,请求类型需要匹配。
$.ajax({
method: "POST",
url: "test_select.php",
data: {speedMbps: speedMbps },
cache: false
}).done(function( html ) {
$( "#results" ).val( html );
});
这是jQuery关于ajax的文档:ajax docs