如何通过js从文本区域向php发送字符串

时间:2018-03-31 10:42:59

标签: javascript php

我试图从js中的textarea获取字符串值并将其发送到我的php文件。但是当我检查接收字符串的变量的值时,它返回“”。但是收到了所有其他价值。

js file

    $(document).ready(function () {


$("#newTestApprove").on("click", function(e) {

   $testimonial = escape(document.getElementById("testimonialArea").value);
   $client = document.getElementById("client").value;
   $event = document.getElementById("event").value;
   $status = "submitted";

   if ($testimonial.length === 0)
   {
       alert("Testimonial Field is left empty");

    }else 
    if ($client.length === 0)
   {
       alert("Client Field is left empty");

        }
        else if ($event.length === 0)
   {
       alert("Event Field is left empty");

   } else{

   obj = {"status":$status, "client":$client, "event":$event, "testimonial":$testimonial};
   dbParam = JSON.stringify(obj);

   xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
   if (this.readyState === 4 && this.status === 200) {
    validity = this.responseText;

    if (validity === "Successful"){
            $('#newTestimonialModal .modal-body').html("Your Testimonial has been Submitted");
            $("#newTestApprove").remove();            
    } 
}  
};


}
 xmlhttp.open("POST", "../php/postTestimonial.php", true);
 xmlhttp.setRequestHeader("Content-type", "application/x-www-form- 
 urlencoded");
 xmlhttp.send("x=" + dbParam);

});


});

php文件

    <?php


   $obj = json_decode($_POST["x"], false);
   $testimonial = $obj->testimonial;

   echo  $testimonial;

   ?>

当我回复$ testimonial时,它返回“”

1 个答案:

答案 0 :(得分:0)

请在javascript中指定变量

  var testimonial=document.getElementById("testimonialArea").value;
而不是 `$证明=逃逸(的document.getElementById(&#34; testimonialArea&#34)的值。);

请尝试以下`例如:

<html>
<body>
Address:<br>
<textarea id="myTextarea"></textarea>
<p>Click the button to alert the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var testimonial = document.getElementById("myTextarea").value;
    document.getElementById("demo").innerHTML = testimonial;
    var obj = {"testimonial":testimonial};
    var dbParam = JSON.stringify(obj);
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML =
        this.responseText;
        }
      };
      xhttp.open("POST", "ajax_info.php", true);
      xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhttp.send("fname="+dbParam);
}
</script>
</body>
</html>

Php文件 - &gt; ajax_info.php

<?php

$obj = json_decode($_POST["fname"], false);
$testimonial = $obj->testimonial;
echo  $testimonial;

?>