2017-08-20 2 views
0

私のプログラムにはajax jqueryとphpを使用しています。私はこのように見えるように、私はテキストフィールドに入力するすべての単語を表示したい:AJAXはテキストフィールドの単語カウンタのすべての入力を更新します

私が入力した場合、「これは、サンプルサンプル単語単語単語である」、出力は次のようになりますように:

//output 
This = 1 
is = 2 
a = 1 
sample = 2 
word = 3 
//end_output 

私の現在コードは、私がテキストボックスに入力したものだけを表示し、それを返します。 index.htmlを

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Working with Javascript</title> 
     <script type="text/javascript" src="js/jquery-3.2.1.min.js"> 
</script> 
    </head> 

    <body> 
     <input type="text" name="input" id="textInput" autofocus/> 
     <div id="content"></div> 
    </body> 
    <script type="text/javascript"> 
     var textInput = document.getElementById("textInput"); 
     var jTextInput = $("#textInput"); 
     var divSelector = document.getElementById("content"); 
     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": "assigned.php", // where to send the request 
       "dataType": "JSON", // datatype of the request 
       "data": { 
        "text": $("#textInput").val() 
       }, //DATA values that you'll sebd 
       success: function (res) { 
        $("#content").html(res.reversedString); 
       } 
      }); 
     }; 
    </script>  
</html> 

と他のページは

<?php 

$var = array("reversedString" => $_POST['text']); 

echo json_encode($var); 
?> 

assigned.phpである私は、PHPのためのアイデアを持っており、それがこの

$text = $_POST['input']; 
    $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>"; 
    } 

のように見えるが、私はどこ見当がつかないそれを置くためには、どのように動作し、それが動作するかどうか。私はassigned.phpに置くことを好みます。あなたの助けをありがとう:)

答えて

1

実際には、これらのコードをassigned.phpに入れるだけで、プレーンテキストとして送信され、フロントエンドがそれらを取得してhtmlに追加できます。

しかし、ウェブ開発データはフロントエンドとバックエンドの間でJSONとして送信され、データを解析する任務はフロントエンドに属します。したがって、PHPでJSONデータを返す方法を変更することを検討することができます。 PHPでJSONを送信したい場合は、header('content-type: application/json')のように設定してください。

+0

ありがとうございました。私はAJAXを初めて習得したときにあなたが何を意味しているかを完全に理解することはできませんが、バイブルは非常に高く評価されています。 –

関連する問題