我试着寻找解决方案,但我不能正确处理它。此外,我希望它显示使用AJAX。因此,每次我键入一个单词时,它都会出现在文本框下面,旁边有一个计数器。我当前的代码是:
输出应该是这样的:输入“敏捷的棕色狐狸”
brown -- 1
fox -- 2
quick -- 1
the -- 1 但我目前的输出是:
brown -- 1
fox -- 1
fox -- 2
quick -- 1
the -- 1
//the fox displays twice.我的index.php
<!DOCTYPE html>
<html>
<head>
<title>Working with Javascript</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js">
</script>
</head>
<body>
<!--textbox-->
<input type="text" name="input" id="textInput" autofocus/>
<!--where the answer will appear-->
<div id="content"></div>
</body>
<script type="text/javascript">
//get the content of the textbox
var textInput = document.getElementById("textInput");
//transform it into jQuery
var jTextInput = $("#textInput");
var divSelector = document.getElementById("content");
//the AJAX function
textInput.onkeyup = function () {
console.log($("#textInput").val());
$.ajax({
"method": "POST", //to specify what type of METHOD to
REQUEST in the SERVER (GET or POST)
"url": "assignment2.php", // where to send the request
"dataType": "JSON", // datatype of the request
"data": {
"text": $("#textInput").val() //DATA values that you'll
send
},
success: function (res) {
$("#content").html(res.reversedString);
}
});
};
</script>
</html>和我的assignment2.php
<?php
/*
//note: if you delete everything and left the commented code below, the text
displays as you type in the textbox.
//$vari = array("reversedString" => $_POST['text']);
//echo json_encode($vari);
*/
////////////////////////////////////////////////////
//get the content of textbox
$vari = array("reversedString" => $_POST['text']);
$var = $vari;
header('Content-Type: application/json;charset=utf-8');
//make it an array
$words = explode(' ', $var);
//sort by a-z
sort($words);
$result = array_combine($words, array_fill(0, count($words), 0));
//total number of words
$len = count($words);
//the array for the number of occurences
$totals = array();
foreach ($words as $word) {
$result[$word] ++;
array_push($totals, $result[$word]);
}
//the array for the words and number of occurences
$finalarray = array();
for ($i = 0; $i < $len; $i++) {
array_push($words[$i] . " -- " . $totals[$i] . " <br>");
}
//make the array back to sentence
$regularexpression = implode(" ", $finalarray);
$last = array("reversedString" => $regularexpression);
echo json_encode($last);我会回答我得到的任何模糊的信息。这是我的作业。请帮助并感谢您的耐心等待:)
发布于 2017-08-21 11:06:13
在for each循环中使用if语句
在推送之前,使用in_array检查它是否在那里。
foreach($words as $word){if(!in_array($word, $liste, true)){
array_push($liste, $word);
}}https://stackoverflow.com/questions/45788708
复制相似问题