我试图使用 GET 方法通过 ajax 发送一个字符串,但是只要该字符串包含一些标点符号,当我在 php 中使用 echo 时,这些字符就不会出现。
例如,如果我发送字符串“sub + 12”,php 将回显“sub 12” 如果我发送“&()*”,php 将回显一个空字符串。
为什么会发生这种情况? 字符串中是否有不能包含的特殊字符?
最佳答案
你encodeURIComponent()
。这是演示代码,您可以查看
类似这样的encodeURIComponent(yourtext)
首先是这个html代码。在文本字段中输入文本并检查此输出,这是 onkeyup,因此输入文本并检查结果
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").keyup(function () {
$('#results').html('');
var searchString = $("#search_box").val();
var data = 'search_text=' + encodeURIComponent(searchString);
if (searchString) {
$.ajax({
type: "GET",
url: 'edit.php',
data: data,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#results').html(result);
//window.location.reload();
}
});
}
});
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button"/><br/>
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
然后创建edit.php文件
<?php
$searchquery = $_GET['search_text'];
echo $searchquery;
?>
然后检查结果。正在运行
输出为
搜索结果:
&()*
关于javascript - 使用 Ajax 向 PHP 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44291063/