dongwei3712 2010-06-30 05:45 采纳率: 100%
浏览 120
已采纳

如何通过Javascript测试是否正确发送POST请求?

Here's the particular situation: I'm using a bookmarklet to call a .js that sends a POST request to a PHP file on my server. Here's the POST request in the .js file:

var snd = ("qu=" + encodeURIComponent(t) + "&dl=" + encodeURIComponent(dl) + "&dt=" + encodeURIComponent(dt));


xr = new XMLHttpRequest();   
xr.open("POST", "http://quotebook.us/s/process2.php",true);
xr.onreadystatechange=function() {
  if (xr.readyState==4) {
    var xmldoc = xr.responseText;
window.alert(xr.responseText);
}
}

xr.send(snd);

And below is what I'm doing in PHP. But try as I might, I can't figure out how to get something BACK to the .js file so it can display it in an alert (and consequently, so I can confirm that it's sending the data in the first place).

<?php

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    echo "This page is not for viewing";
    exit;
} 
$qo = $_POST["qu"];
$dl = $_POST["dl"];
$dt = $_POST["dt"];

echo "First parm: $qo, second param: $dl, third param: $dt";
?>

Ultimately I want to take these variables and write them to a MySQL database, but I'm at least a day away from learning how to do that...

Any help on this process would be very welcome, I've had a heck of a time finding anything about processing POST requests that AREN'T sent by a user form. Apparently writing bookmarklets that send data to MySQL is a black art ;)

  • 写回答

2条回答 默认 最新

  • dongzhuang2030 2010-06-30 05:53
    关注

    To test that you're doing it correctly, I'd probably use Firebug on Firefox or Dev Tools on Chrome; with either, you can see the actual HTTP data sent or received. But I think your real question is, why isn't the POST working? (You might consider updating your question title.)

    And the answer may be that you're not setting the content type. POST is generic, you can post anything. In your case, you're posting URL-encoded data, so try adding:

    xr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    

    ...after your open call. Some examples here and here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?