dongliyan9190 2019-04-14 15:29
浏览 125
已采纳

无法使用post方法在AJAX调用中发送数据

here is my code, its pretty simple and works perfect:

var r = new XMLHttpRequest();
var name='KillerSeba';
r.open("GET","../Serve/servepage.php?name="+name,true);
r.onreadystatechange = function () {
  if (r.readyState != 4 || r.status != 200) return;
  alert("Success: " + r.responseText);
};
r.send();

This code just sends alert "Success: KillerSeba" when page loads. And my php file which answers request looks kinda of:

<?php
$s=$_REQUEST['name'];
echo $s;
?>

Then i want to use POST method instead of GET one. In order to do this, I change "GET" to "POST", changing url to php file, then add name variable to send() function, so my javascript code look like this:

var r = new XMLHttpRequest();
var name='KillerSeba';
r.open("POST","../Serve/servepage.php",true);
r.onreadystatechange = function () {
  if (r.readyState != 4 || r.status != 200) return;
  alert("Success: " + r.responseText);
};
r.send(name);

But now script doesnt send any Data to php file, cuz i getting only "Success:" alert. KillerSeba dissipates to somewhere. I tried to use 'name' and "name" instead of name inside of send() function, i tried to replace $_REQUEST by $_POST, but it still doesnt help. So my Queistion is: How to send Data in AJAX Request using POST method? How does this send() function work? P.S. I prefer to use Vanilla JS Framework only.

  • 写回答

2条回答 默认 最新

  • dongmei9203 2019-04-14 15:38
    关注

    As you're sending the name as string without any paramerter name that's why it is not working for you with POST method but when you're sending with GET you're concatenating that name with the url. Now, you've to pass the params the same way you sent with GET method. Just try like this way, I just wrap the name to a variable called params that contains the params = 'name='+name; so you've to send it with your r.send(params). See the examples here both for GET and POST

    var r = new XMLHttpRequest();
    var name='KillerSeba';
    r.open("POST","../Serve/servepage.php",true);
    //Send the proper header information along with the request
    r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    r.onreadystatechange = function () {
      if (r.readyState != 4 || r.status != 200) return;
      alert("Success: " + r.responseText);
    };
    params = 'name='+name;
    r.send(params);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试