2017-05-31 105 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

不客氣 –