我正在尝试在 jQuery 的帮助下与服务器来回通信。
这是我的简单场景:
- 使用 jQuery post 方法通过 html 表单发送数据。
- 服务器端收到数据后再次回显。
- 在客户端以 jQuery 回调的形式接收相同的数据,并对数据执行一些操作(broser 中的 console.log)
现在我的问题是 php 返回带有标签的源 html 代码,而不是已收到的数据? 因此,如果我在客户端的表单字段中输入“Hello”,php 将从页面返回整个 html 源代码。这是为什么?
HTML:
<form action="#">
<textarea name="content" id="content" rows="8" cols="40"></textarea>
<p><button>Click to submit</button></p>
</form>
jquery:
(function(){
$("form").on("submit",function(e){
$.post("save.php",$(this).serialize(),function(data){
alert(data);
})
e.preventDefault();
})
}());
PHP:
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
<?php
echo $_POST['content'];
?>
<script src=""></script>
</body>
</html>
最佳答案
假设这是你的 save.php :
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
<?php
echo $_POST['content'];
?>
<script src=""></script>
</body>
</html>
只需执行 json_encode 并使用 ajax 调用解析 JSON 即可:
保存.php
<?php
echo json_encode($_POST['content']);
?>
jQuery
$.post("save.php",
$(this).serialize(),
function(data){
alert(data);
}, 'json');
关于php - 为什么我的 PHP 页面响应整个 HTML 源代码,而不仅仅是我正在回显的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14787868/