繁体   English   中英

如何通过JS从文本区域向PHP发送字符串

[英]How to send String from text area to php via js

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

js文件

    $(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时,它返回“”

请在javascript中将变量分配为

  var testimonial=document.getElementById("testimonialArea").value;

而不是`$ testimonial = escape(document.getElementById(“ testimonialArea”)。value);

请在下面尝试,例如:

<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文件-> ajax_info.php

<?php

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

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM