我想在我的项目的php部分放置像word counter这样的条件并使用AJAX显示它。到目前为止,这是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with JavaScript</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<style>
.quicksand{
font-family: 'Quicksand', sans-serif;
}
.centered {
margin: 0 auto; width: 40%;
}
</style>
</head>
<body style="background-color: green"><br><br>
<div class="container">
<div class="centered">
<div class="jumbotron" align="center">
<div class="container">
<h1><div class="quicksand"> Word Counter</div> </h1><br>
<input type="text" name="textInput" id="textInput" class="form-control quicksand"
placeholder="Enter Anything!" autocomplete="off" required autofocus style="text-align: center" />
</div></div>
<div class="jumbotron" align="center"><div id="content" class="quicksand""></div>
</div>
</div></div>
</body>
<script type="text/javascript">
//get the content
var textInput = document.getElementById("textInput");
//the function
textInput.onkeyup = function () {
//AJAX
$.ajax({
//to specify what type of METHOD to REQUEST in the SERVER (GET or POST)
"method": "POST",
// where to send the request
"url": "assignment2.php",
// where to send the request
"dataType": "JSON",
//DATA values that you'll send
"data": {
"text": $("#textInput").val()
},
//if no error
success: function (res) {
var string = res.occurencesString;
$("#content").html(string);
}
});
}
</script>
</html>
和我的php:
<?php
$text = array("occurencesString" => $_POST['text']);
echo json_encode($text);
这是我为字计数器
创建的工作代码<?php
//this $text is just an example, please put this php in a new php file
$text = "The quick brown fox";
$words = explode(' ', $text);
sort($words);
$result = array_combine($words, array_fill(0, count($words), 0));
$len = count($words);
for ($i = 0; $i < $len; $i++) {
echo $words[$i] . " ";
}echo "<br> <br>";
foreach ($words as $word) {
$result[$word] ++;
}
foreach ($result as $word => $count) {
echo "$word $count<br>";
}
?>
我的问题是,我不知道如何把它放在php页面上,因为据我所知,除了这两行之外我在php页面上放的任何内容都会导致不再显示任何内容。 Plz halp并提前感谢:)
答案 0 :(得分:1)
尝试在assignment2.php
中使用此代码。
我认为问题只是因为您在收到输入后立即将文本回显给AJAX。你需要先计算单词。
<?php
$text = $_POST['text'];
$words = explode(' ', $text);
$result = array_combine($words, array_fill(0, count($words), 0));
foreach ($words as $word) {
$result[$word] ++;
}
// sort by most to fewest (optional)
arsort($result);
$response = '';
foreach ($result as $word => $count) {
$response .= $word . ' - ' . $count . '<br/>';
}
$text = array("occurencesString" => $response);
echo json_encode($text);
?>