我想将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";
}
?>
在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";
}
?>
首先,从数据类型中删除脚本。这是你如何将数据传递给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>