2017-05-31 150 views
0

我想通过使用GET方法的ajax发送字符串,但每当该字符串包含一些标点符号时,在php中使用echo时不会出现这些字符。使用Ajax发送数据到PHP

例如,如果我发送一个字符串“sub + 12”,php会回显“sub 12” 如果我发送“&()*”,php会回显一个空字符串。

为什么会发生这种情况? 是否有字符串不能包含的任何特殊字符?

+2

你能告诉相关的代码吗? – JazZ

+1

显示您的代码,您尝试 –

回答

1

you 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; 
?> 

然后检查结果。这是工作

输出是

的搜索结果:

&()* 
+0

非常感谢,encodeURIcomponent是我所需要的! –

+0

不客气 –