我的存储库中有2个文件,我想将index.php中的js变量传递给php脚本validate.php。我的存储库的结构:
index.php中的代码:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
The content of the document......
<script type="text/javascript">
var name = "virginia"
//console.log(name)
$.ajax({
url: "../pdf/validate.php",
method: "post",
data: name,
success: function(res) {
console.log(name)
console.log("pass js variable to php: success")
}
});
// open localhost/index.php
// open F12 developer console, you will find 'virginia' was passed to validate.php, because it console-prints "pass js variable to php: success".
</script>
</body>
</html>
ajax请求成功完成validate.php。但是,转到validate.php,我有:
<?php
$var1 = $_POST['name'];
echo($var1);
?>
如果我在localhost中打开validate.php,则会收到错误消息:注意:未定义的索引:名称。
为什么?
答案 0 :(得分:2)
ajax请求成功验证了。
不太成功。
您没有正确格式化数据以供PHP解析。
您应该将具有name
属性的对象传递给数据。
data: { name },
如果您用res
检查了name
而不是console.log
,则可以判断当前失败。
如果我在localhost中打开validate.php,则会收到错误消息:注意:未定义的索引:名称。
通过在浏览器中键入URL,您将发出与以前使用JavaScript发出的POST请求完全无关的 new GET请求。
第一个请求中的POST数据在第二个请求中不存在。
如果希望数据在请求之间保持不变,则需要将其存储在某个位置(例如会话或数据库),并添加逻辑以区分设置和检索数据(例如,将请求从POST或GET取消)