[英]Not able to POST Variable to Another Page (PHP, Javascript, AJAX)
[英]Ajax not able to post javascript variable to php
我想将 JavaScript 变量的值发布到 PHP 页面,然后在那里使用这些值。
我得到一个新的 HTML 页面,这是我不想发生的。 此外,它显示由以下产生的错误消息:
echo"some error";
我错过了什么? 我不明白为什么会这样?
这是我的 html 文件try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
这是我的 PHP 文件try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
首先,从数据类型中删除脚本。 这是将数据传递给 php 文件的方法:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - 您期望从服务器返回的数据类型。 在这里,您不想要任何回报,那很好。 如果你期待像 json 之类的东西,你可以指定它。
如果你想要任何回应,你可以用这种方式处理 $('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - 当 Ajax 请求成功时执行的回调函数。
首先从链接中删除href。 通过这个它直接重定向到 try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>
在 try.php 中,如果您回显某些内容,它又会返回到 try.html。
如果您只想将数据发布到 try.php 并在那里回显,只需使用表单并提交。 你不需要ajax。 Ajax 是在不重新加载现有页面的情况下发送数据/接收回。 响应将在当前页面本身中看到。
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
在 try.php 页面中,您可以放置此代码
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.