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 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件