Php 在AJAX请求中未收到来自的数据
我测试了我的第一个AJAX表单,但当我提交表单时,警报消息只显示“2”。我搜索将ajax数据发送到同一页面,发现我可以做到,但URL是可选的 我的PHP代码:Php 在AJAX请求中未收到来自的数据,php,jquery,html,ajax,Php,Jquery,Html,Ajax,我测试了我的第一个AJAX表单,但当我提交表单时,警报消息只显示“2”。我搜索将ajax数据发送到同一页面,发现我可以做到,但URL是可选的 我的PHP代码: <html> <body> <form action="index.php" method="post"> <input name="name" type="text" /> <input type="submit" value="submit" na
<html>
<body>
<form action="index.php" method="post">
<input name="name" type="text" />
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST["name"]))
{
$data="test string";
echo json_encode($data);
}
?>
<script src="jquery-2.1.0.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>
我不知道哪里出错了?最好将页面生成和json响应生成委托给不同的页面。至少您应该隔离它,因为页面的以下部分也以ajax响应结束:
<html>
<body>
<form action="index.php" method="post">
<input name="name" type="text" />
<input type="submit" value="submit" name="submit">
</form>
...
<script src="jquery-2.1.0.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>
...
修改脚本后,可以执行以下操作:
<?
if(isset($_POST["name"]))
{
// And don't forget to specify content type!
header("Content-type: application/json");
$data="test string";
echo json_encode($data);
} else {
?>
<html>
<body>
<form action="index.php" method="post">
<input name="name" type="text" />
<input type="submit" value="submit" name="submit">
</form>
<script src="jquery-2.1.0.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>
<? } ?>
echo json\u encode($data)之后的代码>继续执行页面,并将…
添加到字符串中。因此,它不再是json了。如果您只是再次将值发布到index.php,那么就不需要ajax。Ajax用于异步post,即停留在同一页面上,将数据发送到水下的另一个php脚本,而不会中断您所在的页面。只需删除ajax脚本,看看会发生什么happens@u_mulder这意味着我的所有代码都附加到数据字符串???@myfunkyside我想在当前页面上显示一条错误或成功消息,因此我强制使用ajax
<?
if(isset($_POST["name"]))
{
// And don't forget to specify content type!
header("Content-type: application/json");
$data="test string";
echo json_encode($data);
} else {
?>
<html>
<body>
<form action="index.php" method="post">
<input name="name" type="text" />
<input type="submit" value="submit" name="submit">
</form>
<script src="jquery-2.1.0.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>
<? } ?>