我有一个包含一些文本输入的html页面,一些使用ajax来发布来自这些输入的数据的jquery,还有一个用来处理输入数据的php脚本。然后,php脚本返回一些数据。然而,警报中包含了一堆我不想返回的html标记。我不知道它为什么要这么做。
我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="style.css">
<title>HTML Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="example" id="example">
<button type="button" class="btn btn-primary" id="proceed">Proceed</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="code.js"></script>
</body>code.js:
$(document).ready(function () {
$("#proceed").click(function () {
var request = $.post("script.php", { // Post input to php
formData: $("#example").val()
}, function (response) {
console.log(response);
});
});
});script.php:
<!DOCTYPE html>
<html>
<body>
<?php
$example_input = isset($_POST["formData"]) ? $_POST["formData"] : null;
$keywords = preg_split("/[\s,]+/", $example_input);
echo json_encode($keywords);
?>
</body>
</html>如果我在输入中输入值"xyz“,那么最终登录到控制台的内容是:
<!DOCTYPE html>
<html>
<body>
["xyz"]</body>
</html>为什么会发生这种情况?我如何才能仅获取括号内的值?谢谢!
发布于 2019-07-18 00:30:37
这就是PHP的工作方式。<?php ... ?>之外的任何内容都会正常输出。这就是如何将静态HTML (或任何其他语言)与动态结果混合在一起。
应该只返回JSON的脚本不应该在其前后包含任何HTML代码。
发布于 2019-07-18 00:30:28
将您的script.php更改为仅包含php:
<?php
$example_input = isset($_POST["formData"]) ? $_POST["formData"] : null;
$keywords = preg_split("/[\s,]+/", $example_input);
echo json_encode($keywords);
?>然后它将只返回该部分!
https://stackoverflow.com/questions/57080489
复制相似问题