我正在尝试从html文件传递变量,使用jquery和ajax到php文件,我想在那里处理它。我有两个测试文件:
ajax.html
<html>
<head>
<title>ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<link href="ajax.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#call_back").click(function () {
$.post(
"ajax.php", {
value: $("#input_text").val()
},
function (data) {
$("#response_text").val(data);
}
);
});
});
</script>
</head>
<body>
<div id="wrapper">
<h3>Ajax</h3>
<div class="entry-wrapper">
<h4>Data to send to the server</h4>
<input type="text" size="50" id="input_text" />
<input type="button" value="Ajax Callback" id="call_back" />
</div>
<div id="response_wrapper">
<textarea id="response_text"></textarea>
</div>
</div>
</body>
</html>
和ajax.php
<?php
$value = $_POST['value'];
echo "Returned from the server: $value";
?>
html工作正常。如果我在文本字段中输入一个值,它将被传递给php文件,处理并发回以显示在textarea中。 我查看了firebug,控制台中的post标签显示了我输入的值。
问题是我希望能够在php文件中使用该变量,进行算术运算或使用它运行sql查询,但是当我打开php文件时它会显示为未定义的索引。
我已经查看了从jquery到php传递变量的多个线程,但仍然没有找到答案。我不知道问题是什么。建议非常感谢。感谢。
答案 0 :(得分:0)
如果我理解你的问题,你需要在你的网址中定义变量。 例如:
http://yoursite.com/ajax.php?value=yourdata
这样,当您打开文件时,您正在定义您使用ajax请求所做的全部值。如果这不是您想要完成的任务,请尝试重新解释您的问题。
在第一次评论后修改:
<?php
if(isset($_POST['value'])){
//do whatever in here
dowhatever();
}
function dowhatever() {
$value = $_POST['value'];
echo "Returned from the server: $value";
if(value == 'data') {
//run query
}//end if
}
?>
答案 1 :(得分:0)
我假设当你说你可以确认它正在工作时,但是当你直接打开.php文件时,它有未定义的索引,那么我会说这很有道理。如果您直接浏览.php文件,则不会发送任何POST数据。但是,如果您能够键入一些文本,触发提交,并按计划恢复文本,那么它正在工作。