[英]Passing data from javascript to php using ajax?
我正在尝试从我的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'];
}
?>
$.ajax({
type: "POST",
url: "test_select.php",
data: {speedMbps: speedMbps },
cache: false
}).done(function( html ) {
$( "#results" ).val( html );
});
将method:"POST"
更改为type:"POST"
。
您可能想要合并顶部的底部脚本并将其放置在jquery钩子之后,因为存在变量。
另外,您还缺少method: "POST"
我所知,您的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.