我需要获取javascript变量的值并将其放入mysql数据库中。我试图在(test.html)中使用jquery ajax函数将变量发布到单独的PHP文件(external.php)。我不确定为什么它不起作用,我将不胜感激。这是我的两个文件:
这是test.html:
module ApplicationHelper
def full_title(page_title = '')
base_title = 'Ruby On Rails Tutorial'
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
end
end
这是external.php:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
data: { "longitude": longitude }
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
以下代码对我来说非常合适:
external.php文件:
<?php
header('Content-Type: application/json');
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
test.html文件:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
dataType: "json",
data: { "longitude": longitude },
success: function(data){
console.log(data);
}
});
});
</script>
</body>
</html>
另外,请确保您没有将文件作为:
运行file:///C:/Users/XXX/Desktop/XAMPP/htdocs/test.html
如果你这样运行,你会收到这个错误:
XML Parsing Error: no root element found
Location: file:///C:/Users/XXX/Desktop/XAMPP/htdocs/external.php
Line Number 5, Column 3:
您需要做的是运行Apache,然后将文件运行为:
http://localhost/test.html
以下是我得到的截图: